I have two objects. I need to merge them using JavaScript.
let object1 = {
fruits :[apple, orange],
veggies:[carrot, pumpkin],
}
let object2 = {
fruits :[apple, banana, mango],
veggies:[potato, brinjal]
}
Expected output:
let object3 = {
fruits : [apple,orange,banana,mango],
veggies:[carrot,pumpkin,potato,brinjal]
}
Things I tried:
object3 = {...object1, ...object2}
const object3 = (obj1, obj2) => Object.assign({}, ...Object.keys(obj1).map(i => ({[i]:{...obj1[i], ...obj2[i]}}))); console.log(object3(object1, object2));
3
Answers
Use
Set()
and the spread operator...
:Your 2 tries didn’t work because:
Try this:
here’s my code