Classify similar objects into separate objects from array lists

I have an array of elements that I get from the API as the response body.

data = [{id: 1, category: "kitchen", name: "noodles"},
        {id: 2, category: "general", name: "Wi-Fi"},
        {id: 3, category: "sports", name: "Football"},]

I want to iterate over arrays and get such data:

var categorized = {
 kitchen: [{id: 1, category: "kitchen", name: "noodles"}],
 general : [{id: 2, category: "general", name: "Wi-Fi"}],
 sports : [{id: 3, category: "sports", name: "Football"}]
};

Are there any lodash methods or any ES6 shortcuts for this?

+4
source share
2 answers

In response to your question, is there a lodash way? Yes: https://lodash.com/docs/4.17.4#groupBy . For your specific example:

const categorized = _.groupBy(data, 'category');

Edit: you can collapse your function of type groupBy with ES6, as in another example. But if you use lodash anyway, this is much cleaner.

+4
source

array.reduce,

var data = [{
  id: 1,
  category: "kitchen",
  name: "noodles"
}, {
  id: 2,
  category: "general",
  name: "Wi-Fi"
}, {
  id: 3,
  category: "sports",
  name: "Football"
}]


var newData = data.reduce(function(obj, v, i) {

  obj[v.category] = obj[v.category] || [];
  obj[v.category].push(v);
  return obj;

}, {});
console.log(newData);
Hide result

ES6 :

   var newData = data.reduce((obj, v, i)=> {

      obj[v.category] = obj[v.category] || [];
      obj[v.category].push(v);
      return obj;

    }, {});
    console.log(newData);
+2

Source: https://habr.com/ru/post/1666971/


All Articles