使用 Lodash 将对象键转换为具有键值编号的数组

0 javascript arrays object lodash

我有一个产品对象:

products: {
  bread: 1,
  milk: 2,
  cheese: 2,
  chicken: 1,
}
Run Code Online (Sandbox Code Playgroud)

我想要一个包含产品名称的数组,如下所示:

products: ['bread', 'milk', 'milk', 'cheese', 'cheese', 'chicken']
Run Code Online (Sandbox Code Playgroud)

我试图使用lodashwithreduce方法,但我不知道如何在数组中“乘以”这个产品。

我认为这不是一个好主意:

_.reduce(products, (result, value, key) => {
  for(let i = 0; i < value; i++) {
   result.push(key);
  }
  return result;
}, [])
Run Code Online (Sandbox Code Playgroud)

因此,如果有人可以提供帮助,我将不胜感激。

adi*_*iga 5

您可以使用对象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)
Run Code Online (Sandbox Code Playgroud)