daslashi daslashi - 3 months ago 6
Javascript Question

Need to merge objects with the same keys but different values

I want to find the shortest and most beautiful way to convert an array of objects with the same values of the category key:

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


to the one with grouped labels from the same category:

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

Answer

You could use an object as hash table and group the categories.

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; }