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

痴心易碎 提交于 2020-02-12 05:27:06

问题


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', 'green', 'blue', 'red', 'red']

回答1:


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);



回答2:


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)));



回答3:


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']



回答4:


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);



回答5:


var data={ green: 2, blue: 1, red: 2};
var newData=[];
for(let i in data){
    for(let j=0;j<data[i];j++){
        newData.push(i);
    }
}
console.log('newData = ', newData);

output

newData = ["green", "green", "blue", "red", "red"]

 




回答6:


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)



回答7:


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"]


来源:https://stackoverflow.com/questions/56676142/how-to-produce-an-array-from-an-object-where-the-number-of-elements-is-determine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!