0

Here i am having two different objects :

let oldObject = {name:"Dhanush",age:24,sex:"Male",education:"Btech"}
let newObject = {name:"Dhanush kumar S",age:23,sex:"Male"}

result should be comparing this above two objects and check if the key are same , then update the oldObject value with newObject . The result has to be like this

let updatedObject = {name:"Dhanush kumar S",age:23,sex:"Male",education:"Btech"}

I tried by doing something like this, but this doesnt help. Your help is much appreciated.

const compareObjects = () => {
    for (let [key,value] in oldObject) {
        if (newObject.hasOwnProperty(key)) {
            oldObject[newObject[key]] = newObject[value]
            delete oldObject[key]; //remove old entry
        }
    }
    console.log(oldObject)
}
compareObjects()
SDK
  • 1,356
  • 3
  • 19
  • 44
  • 3
    You should be able to simply use `const updatedObject = { ...oldObject, ...newObject }`. – sp00m Oct 12 '20 at 16:32

1 Answers1

2

You can do this by using the spread syntax.

Just spread the old object first followed by the new object.

Matching keys if any would be updated by the values from the new object and new keys in the new object would be added:

let oldObject = {name:"Dhanush",age:24,sex:"Male",education:"Btech"}
let newObject = {name:"Dhanush kumar S",age:23,sex:"Male"}

const merge = (oldObj, newObj) => {
  return {...oldObj, ...newObj};
}
console.log(merge(oldObject, newObject));
adiga
  • 34,372
  • 9
  • 61
  • 83
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44