[英]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.我试图将
lodash
与reduce
方法一起使用,但我不知道如何在数组中“乘”这个产品。
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.因此,如果有人可以提供帮助,我将不胜感激。
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.