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 combine two objects with same value?

I have two objects with the exact same keys but different values, here is the example I’m struggling with:

obj1={
     "cars": ["nissan","toyota","hyundai"],
     "color": ["red","black","white"], 
}
obj2={
     "cars": ["gmc","ford","chevrolet"],
     "color": ["orange","blue","grey"], 
}

I tried using both:

Object.assign(obj1,obj2)

and:

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

let merge1 = {...obj1,...obj2}

but output is always:

{
     "cars": [         "gmc",         "ford",         "chevrolet"     ],
     "color": [         "orange",         "blue",         "grey"     ] 
}

The desired output is:

{
     "cars": [         "nissan",         "toyota",         "hyundai"         "gmc",         "ford",         "chevrolet"     ],
     "color": [         "red",         "black",         "white"         "orange",         "blue",         "grey"     ] 
}

>Solution :

When you spread or assign two objects into another the values from the second object will overwrite the values from the first object.

If you want to merge the values you need to iterate through the object merging relevant values like so:

const obj1 = {
     "cars": ["nissan", "toyota", "hyundai"],
     "color": ["red", "black", "white"],
}
const obj2 = {
     "cars": ["gmc", "ford", "chevrolet"],
     "color": ["orange", "blue", "grey"],
}

let combinedObj = {}

for (const key of Object.keys(obj1)) {
     const obj1KeyValue = obj1[key]
     const obj2KeyValue = obj1[key]

     if (Array.isArray(obj1KeyValue) && Array.isArray(obj2KeyValue)){
          combinedObj[key] = [...obj1KeyValue, ...obj2KeyValue]
     }
}

console.log(combinedObj)
//displays
//{
//  cars: [ 'nissan', 'toyota', 'hyundai', 'nissan', 'toyota', 'hyundai' ],
//  color: [ 'red', 'black', 'white', 'red', 'black', 'white' ]
//}
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