How to produce an array from an object where the number of elements is determined by Object.values?

后端 未结 7 530
感情败类
感情败类 2020-12-22 05:15

I have an object like so:

{ green: 2, blue: 1, red: 2}

How can I turn it into an array that looks like this:

[ \'green\', \         


        
相关标签:
7条回答
  • 2020-12-22 05:18

    Using map and flat if you don't want to use flatMap directly

    const obj = { 
       green: 2, 
       blue: 1, 
       red: 2
    };
    
    const responseArray = Object.entries(obj)
        .map(([key,value]) => {
            return Array(value).fill(key)
    }).flat();
    
    console.log(responseArray);
    //  ["green", "green", "blue", "red", "red"]
    
    0 讨论(0)
  • 2020-12-22 05:24

    Object.entries will do that - it gives a key: value pair of each property in the object. You then use the value to push the key into an array that gives you the desired output.

    var obj = { green: 2, blue: 1, red: 2};
    
    var newArr = [];
    var objEntries = Object.entries(obj);
    
    objEntries.forEach(function(item){
      for(var i = 0; i < item[1]; i++){
       newArr.push(item[0])
      };
    })
    
    console.log(newArr); // gives //[ 'green', 'green', 'blue', 'red', 'red']

    0 讨论(0)
  • 2020-12-22 05:25

    In the case you do not want to deal with polifills for flatMap support in IE etc you can also consider this solution which is based only on Object.keys and Array.forEach:

    let obj = {green: 2, blue: 1, red: 2}, arr=[]
    
    Object.keys(obj).forEach(x => arr.push(...Array(obj[x]).fill(x)))
    
    console.log(arr)

    Another approach you can take to avoid ES6 Array destructuring is via Array.reduce and Object.entries:

    let obj = {green: 2, blue: 1, red: 2}
    
    let r = Object.entries(obj).reduce((r,[k,v]) => r.concat(Array(v).fill(k)),[])
    
    console.log(r)

    0 讨论(0)
  • 2020-12-22 05:31

    This is a neat way with a generator. Perhaps a little overkill for this example.

    function* makeIterator(obj) {
        const keys = Object.keys(obj);
        for (const key of keys) {
            const value = obj[key];
            for (let i = 0; i < value; i++) {
                yield key;
            }
        }
    }
    
    const obj = {green: 2, blue: 1, red: 2};
    console.log(Array.from(makeIterator(obj)));

    0 讨论(0)
  • 2020-12-22 05:31

    Use reduce with Object.entries:

    const obj = { green: 2, blue: 1, red: 2};
    const res = Object.entries(obj).reduce((a, [k, v]) => (a.push(...new Array(v).fill(k)), a), []);
    
    console.log(res);

    0 讨论(0)
  • 2020-12-22 05:34

    Could be done like this:

    Object.entries(obj).flatMap(([k, v]) => Array(v).fill(k));
    

    Example:

    const obj = { green: 2, blue: 1, red: 2};
    const res = Object.entries(obj).flatMap(([k, v]) => Array(v).fill(k));
    console.log(res);

    0 讨论(0)
提交回复
热议问题