最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Loop over object es6 - Stack Overflow

programmeradmin0浏览0评论

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?

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?

Share Improve this question asked Dec 23, 2017 at 16:59 HyruleHyrule 6452 gold badges10 silver badges25 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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)

 Object.entries(object)
  .forEach(([key, times]) => console.log((key + "\n").repeat(times)));

One may use String.prototype.repeat...

"...it feels like it could be done more neatly and readible."

Recursion makes it pretty clean and understandable.

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]);
  }
})
  


You can rearrange things a bit if you know the value will always be greater than 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]);
})

发布评论

评论列表(0)

  1. 暂无评论