简体   繁体   中英

Convert object key to array with values number of key with Lodash

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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