gpt4 book ai didi

javascript - 按相同的属性值对数组进行分组,遍历该数组

转载 作者:行者123 更新时间:2023-11-30 15:10:10 25 4
gpt4 key购买 nike

我有以下数组:

var results = [
{ group: 1,
department: 2,
total: 10 },
{ group: 1,
department: 2,
total: 25 },
{ group: 1,
department: 3,
total: 15 },
{ group: 1,
department: 3,
total: 5 },
{ group: 2,
department: 4,
total: 10},
{ group: 2,
department: 4,
total: 50 }
]

我需要将数组排列成一个二维嵌套数组,其中子数组是第 1 组和第 2 组。子数组也应该是父数组,其子数组按部门排序,如下所示:

var results:[  
{
group1:[
{
department2:[
{
group:1,
department:2,
total:10
},
{
group:1,
department:2,
total:25
},
{
group:1,
department:3,
total:15
}
]
},
{
department3:[
{
group:1,
department:3,
total:5
}
]
}
]
},
{
group2:[
{
department4:[
{
group:2,
department:4,
total:10
},
{
group:2,
department:4,
total:50
}
]
}
]
}
]

这是一个 React 组件,我需要将每个打印成一行,但在完成所有部门组后添加总计,然后在每个组后添加一个,然后在所有内容后添加总计。

也许我把它复杂化了,有更好的方法吗?

最佳答案

var results = [
{ group: 1,
department: 2,
total: 10 },
{ group: 1,
department: 2,
total: 25 },
{ group: 1,
department: 3,
total: 15 },
{ group: 1,
department: 3,
total: 5 },
{ group: 2,
department: 4,
total: 10},
{ group: 2,
department: 4,
total: 50 }
]

var nested_result = {}

results.forEach(obj => {
if(nested_result[obj.group] === undefined) {
nested_result[obj.group] = {};
}
if(nested_result[obj.group][obj.department] === undefined) {
nested_result[obj.group][obj.department] = [];
}
nested_result[obj.group][obj.department].push(obj);
})

console.log(nested_result);

关于javascript - 按相同的属性值对数组进行分组,遍历该数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45223635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com