用Lodash将对象的键转换为具有键值的数组 [英] Convert object key to array with values number of key with Lodash

查看:1045
本文介绍了用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']

我试图将lodashreduce方法一起使用,但是我不知道如何在阵列中将该乘积相乘".

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.

推荐答案

您可以使用该对象的条目

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)

这篇关于用Lodash将对象的键转换为具有键值的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆