Moving around an es6 object

I have an object that looks like this:

const object = {
head: 1,
eyes: 2,
arms: 2,
legs: 3
}

I want to loop over this object, and that is to print the name of each key, for example. eyesfor the sum of the value.

this will lead to:

head
eyes
eyes
arms
arms 
legs 
legs
legs

I currently have this solution, but it seems that it can be done more accurately and easily.

Object.keys(object)
  .map(key => {
    return [...Array(object[key])].map( (_, i) => {
      return console.log(key)
   })

Any suggestions?

+6
source share
3 answers

You can use the Object.entries()and method map()and return a 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)
Run codeHide result

Or you can use reduce()with propagation syntax in an 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)
Run codeHide result
+4
source
 Object.entries(object)
  .forEach(([key, times]) => console.log((key + "\n").repeat(times)));

You can use String.prototype.repeat...

+3
source

"... , ."

.

const object = {
  head: 1,
  eyes: 2,
  arms: 2,
  legs: 3
};

Object.entries(object).forEach(function f([k,v]) {
  if (v) {
    console.log(k);
    f([k, --v]);
  }
})
  
Hide result

, , , 0.

const object = {
  head: 1,
  eyes: 2,
  arms: 2,
  legs: 3
};

Object.entries(object).forEach(function f([k,v]) {
  console.log(k);
  if (--v) f([k, v]);
})
Hide result
+2

All Articles