Convert object key to array with values number of

2020-05-01 08:51发布

问题:

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>