Home > Software design >  How to merge objects in array JavaScript
How to merge objects in array JavaScript

Time:07-12

i have a array like here

    let array = [
  {
    yearBirth : 1995,
    name : 'daniel',
  },
  {
    yearBirth : 1995,
    name : 'avi',
  },
  {
    yearBirth : 1993,
    name : 'john',
  },
  {
    yearBirth : 1993,
    name : 'david',
  },
]

How do I make it something like that?

{yearBirth : [
      {1995 : [{name : 'daniel'},{name : 'avi'}]},
      {1993 : [{name : 'john'},{name : 'david'}]}
    ]}

I tried to do it in a few ways I also looked for solutions here I did not find ... I would love a solution, thanks

CodePudding user response:

You could use reduce to group by yearBirth property,
then put it result in property yearBirth as an array:

let array = [{
    yearBirth: 1995,
    name: "daniel",
  },
  {
    yearBirth: 1995,
    name: "avi",
  },
  {
    yearBirth: 1993,
    name: "john",
  },
  {
    yearBirth: 1993,
    name: "david",
  },
];
const grouped = array.reduce(function (acc, val) {
    (acc[val.yearBirth] = acc[val.yearBirth] || []).push(val);
    return acc;
}, {});

let output = {
    yearBirth: [grouped]
}
console.log(output);

if you don't get the part of grouping there's a utility library called underscorejs with method groupBy

const grouped = _.groupBy(array, "yearBirth");

Also there are other methods to groupby on an array of objects without third-party library see

  • Related