Search code examples
javascriptnode.jsarraysreactjsjavascript-objects

Merge array of javascript objects


This is the array of javascript objects. I want these javascript objects will merge into a single javascript object according to their same property value.

This is the original array:

const array = [
 {email: '[email protected]', name: 'Jon', role: 'Player', Education: {…}},
 {email: '[email protected]', name: 'Jon', role: 'Player', Skills: {…}},
 {email: '[email protected]', name: 'Jon', role: 'Player', Total: {…}},
 {email: '[email protected]', name: 'Jon', role: 'Player', Personal: {…}},
 {email: '[email protected]', name: 'Tayyab', role: 'Lead', Ethics: {…}},
 {email: '[email protected]', name: 'Tayyab', role: 'Lead', Total: {…}},
 {email: '[email protected]', name: 'Arya', role: 'Banker', Total: {…}},
 {email: '[email protected]', name: 'Arya', role: 'Banker', Skills: {…}},
 {email: '[email protected]', name: 'Arya', role: 'Banker', Personal: {…}},
 {email: '[email protected]', name: 'Arya', role: 'Banker', Education: {…}},
]

This is the required array:

const array = [
 {email: '[email protected]', name: 'Jon', role: 'Player', Education: {…}, Skills: {…}, Total: {…}, Personal: {…}},
 {email: '[email protected]', name: 'Tayyab', role: 'Lead', Ethics: {…}, Total: {…}},
 {email: '[email protected]', name: 'Arya', role: 'Banker', Total: {…}, Skills: {…}, Personal: {…}, Education: {…}},
]

Like email, name, and role all three have the same property and property value. It would merge into one javascript object and the others remain the same. Kindly provide the solution in React.js/Javascript. Thanks


Solution

  • A good case to apply reduce method, try this code:

    const array = [
     {email: '[email protected]', name: 'Jon', role: 'Player', Education: {}},
     {email: '[email protected]', name: 'Jon', role: 'Player', Skills: {}},
     {email: '[email protected]', name: 'Jon', role: 'Player', Total: {}},
     {email: '[email protected]', name: 'Jon', role: 'Player', Personal: {}},
     {email: '[email protected]', name: 'Tayyab', role: 'Lead', Ethics: {}},
     {email: '[email protected]', name: 'Tayyab', role: 'Lead', Total: {}},
     {email: '[email protected]', name: 'Arya', role: 'Banker', Total: {}},
     {email: '[email protected]', name: 'Arya', role: 'Banker', Skills: {}},
     {email: '[email protected]', name: 'Arya', role: 'Banker', Personal: {}},
     {email: '[email protected]', name: 'Arya', role: 'Banker', Education: {}},
    ]
    
    let result = Object.values(array.reduce((acc, {name, ...rest}) => {
        acc[name] = {...acc[name], ...{name, ...rest}};
        return acc;
    }, {}));
    
    console.log(result);