我想找到一种最短,最漂亮的方法来转换具有相同类别键值的对象数组:
[{
"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"
}]
答案 0 :(得分:4)
您可以将对象用作哈希表并对类别进行分组。
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; }

答案 1 :(得分:2)
以下是我将如何使用lodash:
_(coll)
.groupBy('category')
.map((v, k) => ({
category: k,
label: _.map(v, 'label')
}))
.value()
基本上,groupBy()创建一个具有唯一类别作为键的对象。然后,map()将此对象转换回数组,其中每个项目都具有您需要的结构。
答案 2 :(得分:1)
以下是我尝试解决您的问题
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);
&#13;