简体   繁体   English

使用 Lodash 将 object 键转换为具有键值的数组

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

I have an object with products:我有一个带有产品的 object:

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.我试图将lodashreduce方法一起使用,但我不知道如何在数组中“乘”这个产品。

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.因此,如果有人可以提供帮助,我将不胜感激。

You could use flatMap over the entries of the object您可以在 object 的条目上使用flatMap

 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)

With lodash you can iterate the array with _.flatMap() .使用 lodash,您可以使用_.flatMap()迭代数组。 Create the the callback using _.overArgs() that will pass the value (via _.identity() ) and the key (wrapped with _.constant() ) to _.times() :使用_.overArgs()创建回调,它将值(通过_.identity() )和密钥(用_.constant()包装)传递给_.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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM