I have an object which looks like this:
const object = {
head: 1,
eyes: 2,
arms: 2,
legs: 3
}
I want to loop over this object and this and log out each key name e.g. eyes
for the amount of the value.
this would result in:
head
eyes
eyes
arms
arms
legs
legs
legs
Currently I have this solution but it feels like it could be done more neatly and readible.
Object.keys(object)
.map(key => {
return [...Array(object[key])].map( (_, i) => {
return console.log(key)
})
Any suggestions?
You could use Object.entries()
and map()
method and return new array.
const object = {head: 1,eyes: 2,arms: 2,legs: 3}
const res = [].concat(...Object.entries(object).map(([k, v]) => Array(v).fill(k)))
console.log(res)
Or you could use reduce()
with spread syntax in array.
const object = {head: 1,eyes: 2,arms: 2,legs: 3}
const res = Object
.entries(object)
.reduce((r, [k, v]) => [...r, ...Array(v).fill(k)], [])
// Or you can use push instead
// .reduce((r, [k, v]) => (r.push(...Array(v).fill(k)), r), [])
console.log(res)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With