Skip to content
Advertisement

Restructure array based on a particular key together- javascript

I have an object array like so:

 const data = [
    {category: {id: 1, name: 'beverage'}, title: 'Tea'},
    {category: {id: 1, name: 'beverage'}, title: 'Coffee'},
    {category: {id: 2, name: 'snacks'}, title: 'French fries'},
  ];

I want the result like so:

const transformed = [
  {
    category: "beverage",
    data: [{title:'coffee'},{title:'tea'}, ...]
  },
  {
    category: "snacks",
    data: [{title:'french fries'},...]
  },
..
]

What i did was:

 let transformed = data?.map(function (obj) {
    var result = {
      category: obj.category.title,
      data: [],
    };
    for (var key in obj) {
      if (obj.hasOwnProperty(key) && key === 'category') {
        result.values.push(obj);
      }
    }

    return result;
  });

But with this approach i am getting duplicate category names for every object in the array.

Advertisement

Answer

As with all grouping operations the key is to use reduce to build up a new object.

const data = [
    {category: {id: 1, name: 'beverage'}, title: 'Tea'},
    {category: {id: 1, name: 'beverage'}, title: 'Coffee'},
    {category: {id: 2, name: 'snacks'}, title: 'French fries'},
  ];
  
const result = Object.values(data.reduce( (a,i) => {
    a[i.category.id] = a[i.category.id] || {category:i.category.name, data:[]};
    a[i.category.id].data.push({title:i.title});
    return a;
},{}));

console.log(result);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement