Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop over object es6

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?

like image 315
Hyrule Avatar asked Dec 23 '17 16:12

Hyrule


1 Answers

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)
like image 137
Nenad Vracar Avatar answered Sep 20 '22 00:09

Nenad Vracar