Home > OS >  concatenate Multiple Json object with a key value in Nodejs
concatenate Multiple Json object with a key value in Nodejs

Time:10-26

suppose I have a array of json object:

[
  {
    name: "abc",
    class: "12"
  },
  {
    name: "abc",
    Roll: "12"
  },
  {
    name: "def",
    class: "10"
  },
  {
    name: "def",
    Roll: "15"
  }
]

So, I need a ouput of , something like that:

[
  {
    name: "abc",
    class: "12",
    Roll: "12"
  },
  {
    name: "def",
    class: "10",
    Roll: "15"
  }
]

CodePudding user response:

One solution would be to group objects together by name. After we have the groups, we can merge the objects from each group.

function groupBy(array, key) {
    return array.reduce((prev, current) => {
        (prev[current[key]] = prev[current[key]] || []).push(current);
        return prev;
    }, {});
}


function main(array) {
    // Group by objects by name
    const groups = groupBy(array, 'name');
    
    // Iterate through groups and merge the list of objects together 
    const result = Object.values(groups).map(group => group.reduce((prev, current) => {
        return {...prev, ...current};
    }));
    return result;
}

const objects = [
    {
        name: "abc",
        class: "12"
    },
    {
        name: "abc",
        Roll: "12"
    },
    {
        name: "def",
        class: "10"
    }, {
        name: "def",
        Roll: "15"
    }];
    
console.log(main(objects));
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related