I need to merge 2 objects of objects. I have tried both the spread operator and Object.assign. But my end result still is showing just the results of the second objects.
let obj1= { ratings: [], stats: {restaurants: 0, bnb: 0, hotel: 0}, calls: [ {f_name: 'Harry', l_name: 'Potter', address: 'Godrics Hollow', colors:['red', 'gold']}, {f_name: 'Ron', l_name: 'Weasley', address: 'The Burrow', colors:['orange', 'black']}, {f_name: 'Hermione', l_name: 'Granger', address: '123 London', colors:['red', 'blue']}, ] } let obj2= { ratings: [], stats: {restaurants: 3, bnb: 2, hotel: 1}, calls: [ {f_name: 'Jon', l_name: 'Snow', address: 'The Wall', colors:['white', 'brown']}, {f_name: 'Robb', l_name: 'Stark', address: 'Winterfell', colors:['red', 'white']}, {f_name: 'Sansa', l_name: 'Stark', address: 'The North', colors:['white', 'silver']}, {f_name: 'Arya', l_name: 'Stark', address: 'Essos', colors:['blue', 'silver']}, {f_name: 'Bran', l_name: 'Stark', address: 'Kings Landing', colors:['purple', 'green']} ] } let obj3 = { ...obj1, ...obj2 }; console.log(obj3); console.log('---------------------------------------------'); let obj4 = Object.assign(obj1, obj2); console.log(obj3); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> Both ways are returning: obj2.
I need:
{ ratings: [], stats: {restaurants: 3, bnb: 2, hotel: 1}, calls: [ {f_name: 'Harry', l_name: 'Potter', address: 'Godrics Hollow', colors:['red', 'gold']}, {f_name: 'Ron', l_name: 'Weasley', address: 'The Burrow', colors:['orange', 'black']}, {f_name: 'Hermione', l_name: 'Granger', address: '123 London', colors:['red', 'blue']}, {f_name: 'Jon', l_name: 'Snow', address: 'The Wall', colors:['white', 'brown']}, {f_name: 'Robb', l_name: 'Stark', address: 'Winterfell', colors:['red', 'white']}, {f_name: 'Sansa', l_name: 'Stark', address: 'The North', colors:['white', 'silver']}, {f_name: 'Arya', l_name: 'Stark', address: 'Essos', colors:['blue', 'silver']}, {f_name: 'Bran', l_name: 'Stark', address: 'Kings Landing', colors:['purple', 'green']} ] }
obj3.calls = [...obj1.calls, ...obj2.calls]? Same forstatsandratings--combine by hand? I'm not sure if this is what you're asking for though.Object.assign(obj1, obj2)is used to copy the properties from source(obj2)to target(obj1). If the properties already exists inobj1, then it will be replaced byobj2. It's not like deep merging of property values. .