Convert object key to array with values number of key with Lodash [duplicate]

风格不统一 提交于 2020-02-16 08:39:28

问题


I have an object with products:

products: {
  bread: 1,
  milk: 2,
  cheese: 2,
  chicken: 1,
}

I would like to have an array with the name of products like this:

products: ['bread', 'milk', 'milk', 'cheese', 'cheese', 'chicken']

I was trying to use lodash with reduce method but I don't know how to "multiply" this product in array.

I think this is not a good idea:

_.reduce(products, (result, value, key) => {
  for(let i = 0; i < value; i++) {
   result.push(key);
  }
  return result;
}, [])

So if anyone could help, I will be grateful.


回答1:


You could use flatMap over the entries of the object

const products = {
  bread: 1,
  milk: 2,
  cheese: 2,
  chicken: 1,
}

const output = Object.entries(products).flatMap(([k, v]) => Array(v).fill(k))

console.log(output)



回答2:


With lodash you can iterate the array with _.flatMap(). Create the the callback using _.overArgs() that will pass the value (via _.identity()) and the key (wrapped with _.constant()) to _.times():

const obj = {
  products: {
    bread: 1,
    milk: 2,
    cheese: 2,
    chicken: 1,
  }
}

const result = _.flatMap(obj.products, _.overArgs(_.times, [_.identity, _.constant]))
  
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>


来源:https://stackoverflow.com/questions/58267051/convert-object-key-to-array-with-values-number-of-key-with-lodash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!