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