3

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"
}]

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

Here is my attempt to solve your problem

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.