问题
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