![](/img/trans.png)
[英]I need to merge objects. They all have the same keys but differing numerical values. I need to get the sum of values for each key
[英]Need to merge objects with the same keys but different values
我想找到最短,最漂亮的方法来转换具有相同类别键值的对象数组:
[{
"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; }
这是我尝试解决您的问题
var result = []; var input = [{ "label": "Apple", "category": "Fruits" }, { "label": "Orange", "category": "Fruits" }, { "label": "Potato", "category": "Vegetables" }, { "label": "Tomato", "category": "Vegetables" }, { "label": "Cherry", "category": "Berries" }]; var cat = []; for(i = 0; i < input.length; i++) { if(!cat[input[i].category]) { cat[input[i].category] = {category: input[i].category, label:[input[i].label]}; result.push(cat[input[i].category]); } else { cat[input[i].category].label.push(input[i].label); } } console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.