我想知道是否有一种方法可以根据值动态地将对象添加到对象数组中?例如,我有一个对象数组:
[
{category:A, num:5},
{category:B, num:2}
]
我想创建另一个对象数组,其中对象是相同的,但根据num的值进行重复(因此类别A重复5次,类别B重复2次):
[
{category:A, num:5, repeated:1},
{category:A, num:5, repeated:2},
{category:A, num:5, repeated:3},
{category:A, num:5, repeated:4},
{category:A, num:5, repeated:5},
{category:B, num:2, repeated:1},
{category:B, num:2, repeated:2}
]
我尝试过map、forEach、for循环,但都不起作用。我是javascript的新手,有人能帮上忙吗?
发布于 2020-09-29 22:25:35
您可以使用flatMap
和map
的组合来完成此操作
var input = [
{category:"A", num:5},
{category:"B", num:2}
] ;
var result = input.flatMap(e => [...new Array(e.num)].map( (x,i) => ({
category:e.category,
num: e.num,
repeated: i+1
})));
console.log(result);
发布于 2020-09-29 22:25:05
您可以使用flatMap来完成此操作-
const repeat = ({ num = 0, ...t }) =>
num === 0
? []
: [ ...repeat({ ...t, num: num - 1 }), { ...t, num, repeated: num } ]
const input =
[ { category: "A", num: 5}, { category: "B", num: 2 } ]
const output =
input.flatMap(repeat)
console.log(output)
输出-
[
{ category: "A", num: 1, repeated: 1 },
{ category: "A", num: 2, repeated: 2 },
{ category: "A", num: 3, repeated: 3 },
{ category: "A", num: 4, repeated: 4 },
{ category: "A", num: 5, repeated: 5 },
{ category: "B", num: 1, repeated: 1 },
{ category: "B", num: 2, repeated: 2 }
]
https://stackoverflow.com/questions/64121355
复制相似问题