Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
}]
like image 593
daslashi Avatar asked Jan 19 '26 10:01

daslashi


2 Answers

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; }
like image 93
Nina Scholz Avatar answered Jan 22 '26 01:01

Nina Scholz


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.

like image 44
Adam Boduch Avatar answered Jan 22 '26 00:01

Adam Boduch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!