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

How to merge array of objects by its key in javascript

I have a array of objects like these:

[
  {
    user: {
      key1: ['1', '2', '3'],
    },
  },
  {
    user: {
      key2: ['3', '4', '5'],
    },
  },
  {
    user2: {
      key1: ['1', '2', '3'],
    },
  },
  {
    user2: {
      key2: ['3', '4', '5'],
    },
  },
....
];

And I need to filter those by its keys and expecting an output like these

[
    {
        user: {
            key1: ['1', '2', '3'],
            key2: ['3', '4', '5'],
        },
    },
    {
        user2: {
            key1: ['1', '2', '3'],
            key2: ['3', '4', '5'],
            ....
        }
    }
]

Here user, user2 can be any key(userName) also key1, key 2 etc… may be any key(userActivity) with an array of string.

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

Here is the type of object:

[key: string]: {
    [key: string]: string[];
  };
}[];

Which will be the best way to filter this any help would be appreciated

>Solution :

You can do it with reduce() method:

  • Iterate over each item from the data array
  • Check if the key from item already exists in final result
  • If it exists, concatenate current value and new value
  • If it does not exist, initialize new value
const data = [
 { user: { key1: ['1', '2', '3'] } },
 { user: { key2: ['3', '4', '5'] } },
 { user2: { key1: ['1', '2', '3'] } },
 { user2: { key2: ['3', '4', '5'] } }
];

const result = data.reduce((accumulator, currentValue)=>{
  const currentKey = Object.keys(currentValue)[0];
  
  if(Object.keys(accumulator).includes(currentKey)) {
     accumulator[currentKey] = {...accumulator[currentKey], ...currentValue[currentKey]};
  } else {
     accumulator[currentKey] = currentValue[currentKey];
  }
  
  return accumulator;
},{})

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