gpt4 book ai didi

javascript - 按属性分组对象

转载 作者:行者123 更新时间:2023-11-29 10:05:59 27 4
gpt4 key购买 nike

我的问题有点类似于javascript | Object grouping .

我的输入对象是

[
{
"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"
}
]

我需要的输出是

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

]

当我尝试实现答案时,我得到了

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

我不想将具有相同属性的对象分组到一个数组中。我找不到他们将其插入数组的位置。帮我修一下:(

最佳答案

您可以对项目进行分组并将所有组连接到一个数组中。

It works by generating an object with the group as property an the items as items in the array.

In the next step, the object's values are taken and a new array is generated by concatination of the items with Array#reduce.

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

var data = [{ 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" }],
groups = Object.create(null),
result = [];

data.forEach(function (a) {
groups[a.group] = groups[a.group] || [];
groups[a.group].push(a);
});

result = Object.keys(groups).reduce(function (r, k) {
return r.concat(groups[k]);
}, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

或者只按排序。

var data = [{ 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" }];

data.sort(function (a, b) {
return a.group.localeCompare(b.group);
});

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

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