gpt4 book ai didi

javascript - 需要合并具有相同键但不同值的对象

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:31:13 25 4
gpt4 key购买 nike

我想找到最短和最漂亮的方法来转换具有相同类别键值的对象数组:

[{
"label": "Apple",
"category": "Fruits"
}, {
"label": "Orange",
"category": "Fruits"
}, {
"label": "Potato",
"category": "Vegetables"
}, {
"label": "Tomato",
"category": "Vegetables"
}, {
"label": "Cherry",
"category": "Berries"
}]

到具有来自同一类别的分组标签的标签:

[{
"label": ["Apple", "Orange"],
"category": "Fruits"
}, {
"label": ["Potato", "Tomato"],
"category": "Vegetables"
}, {
"label": ["Cherry"],
"category": "Berries"
}]

最佳答案

您可以使用一个对象作为哈希表并对类别进行分组。

var data = [{ "label": "Apple", "category": "Fruits" }, { "label": "Orange", "category": "Fruits" }, { "label": "Potato", "category": "Vegetables" }, { "label": "Tomato", "category": "Vegetables" }, { "label": "Cherry", "category": "Berries" }],
grouped = [];

data.forEach(function (a) {
if (!this[a.category]) {
this[a.category] = { label: [], category: a.category };
grouped.push(this[a.category]);
}
this[a.category].label.push(a.label);
}, Object.create(null));

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

关于javascript - 需要合并具有相同键但不同值的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39413124/

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