在JavaScript中对嵌套数组进行分组
假设我们有一个像这样的值数组-
const arr = [
{
value1:[1,2],
value2:[{type:'A'}, {type:'B'}]
},
{
value1:[3,5],
value2:[{type:'B'}, {type:'B'}]
}
];我们需要编写一个包含一个这样的数组的JavaScript函数。然后,我们的函数应该准备一个数组,其中根据对象的“type”属性对数据进行分组。
因此,对于上述数组,输出应类似于-
const output = [
{type:'A', value: [1,2]},
{type:'B', value: [3,5]}
];示例
为此的代码将是-
const arr = [
{
value1:[1,2],
value2:[{type:'A'}, {type:'B'}]
},
{
value1:[3,5],
value2:[{type:'B'}, {type:'B'}]
}
];
const groupValues = (arr = []) => {
const res = [];
arr.forEach((el, ind) => {
const thisObj = this;
el.value2.forEach(element => {
if (!thisObj[element.type]) {
thisObj[element.type] = {
type: element.type,
value: []
}
res.push(thisObj[element.type]);
};
if (!thisObj[ind + '|' + element.type]) {
thisObj[element.type].value =
thisObj[element.type].value.concat(el.value1);
thisObj[ind + '|' + element.type] = true;
};
});
}, {})
return res;
};
console.log(groupValues(arr));输出结果
控制台中的输出将是-
[
{ type: 'A', value: [ 1, 2 ] },
{ type: 'B', value: [ 1, 2, 3, 5 ] }
]热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短