gpt4 book ai didi

javascript |对象分组

转载 作者:可可西里 更新时间:2023-11-01 02:13:28 43 4
gpt4 key购买 nike

我有一个对象。如下所示:

[
{
"name":"Display",
"group":"Technical detals",
"id":"60",
"value":"4"
},
{
"name":"Manufacturer",
"group":"Manufacturer",
"id":"58",
"value":"Apple"
},
{
"name":"OS",
"group":"Technical detals",
"id":"37",
"value":"Apple iOS"
}
]

我想按组字段对这些数据进行分组并得到这个对象:

var obj = {
0 = [
{
'group' = 'Technical detals',
'name' = 'Display',
'id' = '60',
'value' = '4'
},
{
'group' = 'Technical detals',
'name' = 'OS',
'id' = '37',
'value' = 'Apple iOS'
}],
1 = [
{
'group' = 'Manufacturer',
'name' = 'Manufacturer',
'id' = '58',
'value' = 'Apple'
}]
}

如何对我的第一个对象进行分组?

最佳答案

Reduce非常适合这样的情况。给定下面的 list 是您的输入数据:

const list = [{
'name': 'Display',
'group': 'Technical detals',
'id': '60',
'value': '4'
},
{
'name': 'Manufacturer',
'group': 'Manufacturer',
'id': '58',
'value': 'Apple'
},
{
'name': 'OS',
'group': 'Technical detals',
'id': '37',
'value': 'Apple iOS'
}
];

const groups = list.reduce((groups, item) => {
const group = (groups[item.group] || []);
group.push(item);
groups[item.group] = group;
return groups;
}, {});

console.log(groups);

如果你想不可变,你可以这样写 reduce:

const list = [{
'name': 'Display',
'group': 'Technical detals',
'id': '60',
'value': '4'
},
{
'name': 'Manufacturer',
'group': 'Manufacturer',
'id': '58',
'value': 'Apple'
},
{
'name': 'OS',
'group': 'Technical detals',
'id': '37',
'value': 'Apple iOS'
}
];

const groups = list.reduce((groups, item) => ({
...groups,
[item.group]: [...(groups[item.group] || []), item]
}), {});

console.log(groups);

取决于您的环境是否允许传播语法。

关于javascript |对象分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21776389/

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