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"
}]
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; }
Here's how I would do this using lodash:
_(coll)
.groupBy('category')
.map((v, k) => ({
category: k,
label: _.map(v, 'label')
}))
.value()
Basically, groupBy() creates an object with unique categories as keys. Then, map() turns this object back into an array, where each item has the structure you need.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With