Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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.

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading