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

Merge values with same key in object Javascript

What is the best way to merge array contents from JavaScript objects sharing a key in common?

How can array in the example below be reorganized into output? Here, all value keys (whether an array or not) are merged into all objects sharing the same name key.

const array = 
[
  {
    brand: ['Adidas', 'Nike']
    color: ['red']
  },
  {
    brand: ['Puma', 'Nike'],
    size: ['31', '32']
  }
]

/* Expect output
[{
  brand: ['Adidas', 'Puma', 'Nike'],
  size: ['31', '32']
  color: ['red']
}] 
*/

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

>Solution :

This should work

const array = 
[
  {
    brand: ['Adidas', 'Nike'],
    color: ['red']
  },
  {
    brand: ['Puma', 'Nike'],
    size: ['31', '32']
  }
]

const res = array.reduce((prev, curr) => {
   for(let key in curr) {
      if(!prev[key]) {
          prev[key] = curr[key]
      } else {
          prev[key].push(...curr[key])
      }
   }
   return prev
}, {})

console.log(res)
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