Advertisements
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:
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' ]
//}