如何基于动态变量将元素推入数组 [英] How to push elements into array based on dynamic variable

查看:40
本文介绍了如何基于动态变量将元素推入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象,我想用对象属性填充数组,并根据其值重复每个属性多次.一个例子:

I have an object and I want to fill an array with the object property and repeat each property a number of times, based on its value. An example:

obj = {
   watches: 3
   rings: 1
}
// => ['watches', 'watches', 'watches', 'rings']

以下是我到目前为止的内容.我很难确定如何根据关联的值重复每个属性?

Below is what I have so far. I'm having a hard time figuring how to repeat each property based on the associated value?

function arrayBuilder(obj) {
  let objToArr = [];

  for (let [property, value] of Object.entries(obj)) {
    objToArr.push(property);
  }
  return objToArr;
}

console.log(arrayBuilder({watches: 3, rings: 1}));
// => [ 'watches', 'rings' ]

推荐答案

您可以使用

You can use Array.flatMap() (note the support) with Array.fill():

const obj = {
   watches: 3,
   rings: 1
}

const result = Object.entries(obj).flatMap(([k, v]) => Array(v).fill(k));

console.log(result);

Array.reduce() 数组传播,如果不支持flatMap:

Or Array.reduce() with array spread, if flatMap is not supported:

const obj = {
   watches: 3,
   rings: 1
}

const result = Object.entries(obj)
  .reduce((r, [k, v]) => [...r, ...Array(v).fill(k)], []); // or r.concat(Array(v).fill(k)) instead of the spread

console.log(result);

这篇关于如何基于动态变量将元素推入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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