-4

This is my data.

[
 {
  "author":
   {
     "id":"101",
     "label:"abc"
   },
   "books":
   {
      "id":"1"
   }
 },
  {
   "author":
   {
     "id":"101",
     "label:"abc"
   },
   "books":
   {
      "id":"2"
   }
  }
]

In the above array contains list of objects, first object first property and second object first property values are same any time, but remaining properties values are different from every time. so different properties values are push into one array like , i want to get output like this

Output:-

[
{
   "author":
   {
     "id":"101",
     "label:"abc",
     "books":[
      {"id":"1"},
      {"id":"2"}
      ]
   }
}
]
mplungjan
  • 169,008
  • 28
  • 173
  • 236

1 Answers1

0

I can help you out ;) You can use Array.prototype.reduce and ES6 deep object destructuring assignment for aggregation of data, and Array.prototype.map - for generating the desired output:

const data = [{author:{id:"101",label:"abc"},books:{id:"1"}},{author:{id:"101",label:"abc"},books:{id:"2"}}];

const dataObj = data.reduce((all, { author: { id: author_id, label }, books: { id: book_id } }) => {

    if (!all.hasOwnProperty(author_id)) {
        all[author_id] = { id: author_id, label, books: [] };
    }

    all[author_id].books.push({ id: book_id });

    return all;

}, {});

const result = Object.keys(dataObj).map(k => ( { author: dataObj[k] } ) );

console.log(result);
Leonid Pyrlia
  • 1,594
  • 2
  • 11
  • 14