问题
I have an object and I want to fill an array with the object property and repeat each property a number of times, based on its value. An example:
obj = {
watches: 3
rings: 1
}
// => ['watches', 'watches', 'watches', 'rings']
Below is what I have so far. I'm having a hard time figuring how to repeat each property based on the associated value?
function arrayBuilder(obj) {
let objToArr = [];
for (let [property, value] of Object.entries(obj)) {
objToArr.push(property);
}
return objToArr;
}
console.log(arrayBuilder({watches: 3, rings: 1}));
// => [ 'watches', 'rings' ]
回答1:
You were just missing an inner loop:
function arrayBuilder(obj) {
let objToArr = [];
for (let [property, value] of Object.entries(obj)) {
for(var i=0; i<value; i++){
objToArr.push(property);
}
}
return objToArr;
}
console.log(arrayBuilder({watches: 3, rings: 1}));
回答2:
You can use Array.flatMap() (note the support) with Array.fill():
const obj = {
watches: 3,
rings: 1
}
const result = Object.entries(obj).flatMap(([k, v]) => Array(v).fill(k));
console.log(result);
Or Array.reduce() with array spread, if flatMap is not supported:
const obj = {
watches: 3,
rings: 1
}
const result = Object.entries(obj)
.reduce((r, [k, v]) => [...r, ...Array(v).fill(k)], []); // or r.concat(Array(v).fill(k)) instead of the spread
console.log(result);
回答3:
Just add another loop:
for (let [property, value] of Object.entries(obj)) {
for(let i = 0; i < value; i++) {
objToArr.push(property);
}
}
回答4:
To achieve expected result, use below option using repeat and split methods
var obj = {
watches: 3,
rings: 1
}
let result = []
for(key in obj){
result.push(...key.concat(" ").repeat(obj[key]).trim().split(" "))
}
console.log(result)
codepen - https://codepen.io/nagasai/pen/ZVzoGB?editors=0010
回答5:
Go through the keys, for each key, create an array of the required length, fill the resulting array with the names of the key, and combine the resulting arrays:
function arrayBuilder(obj) {
return [].concat.apply(
[],
Object
.entries(obj)
.map(([key, value]) => new Array(value).fill(key))
)
}
console.log(arrayBuilder({watches: 3, rings: 1}))
回答6:
You can do this via Array.reduce and Object.keys:
const obj = { watches: 3, rings: 1 }
const result = Object.keys(obj).reduce((acc, key) =>
[...acc, ...new Array(obj[key]).fill(key)], [])
console.log(result)
The idea is to get the keys from the object and use them to get the length of the array needed for the Array.fill. Using Array.fill
you can fill the array with the same values once you have it setup with the correct length.
来源:https://stackoverflow.com/questions/53677723/how-to-push-elements-into-array-based-on-dynamic-variable