This question already has answers here:
Closed 3 months ago.
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.
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)
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>