Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Categorize Similar items into separate objects from Array lists

I have an array of items that I get from API as a 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 the arrays, and get the data like :

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

Is there any lodash methods, or any ES6 shortcuts for this ?

like image 468
Anonymous Zombie Avatar asked Feb 06 '23 08:02

Anonymous Zombie


2 Answers

In answer to your question 'is there a lodash method?' Yes: https://lodash.com/docs/4.17.4#groupBy. For your specific example:

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

Edit: You could roll your own groupBy type function with ES6 as in another example. But if you are using lodash anyway this is a whole lot cleaner.

like image 84
KaeyangTheG Avatar answered Feb 07 '23 22:02

KaeyangTheG


I used array.reduce to get the structure

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

In ES6 you could so using:

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

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

    }, {});
    console.log(newData);
like image 42
Sandeep Nayak Avatar answered Feb 07 '23 23:02

Sandeep Nayak