我想知道是否有一种方法可以基于值将对象动态添加到对象数组中?例如,我有一个对象数组:
[
{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很陌生,有人可以提供帮助!
答案 0 :(得分:1)
您可以使用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 }
]
答案 1 :(得分:1)
您可以结合使用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);