Skip to content
Advertisement

How to compare two objects in javascript and get difference?

I have two objects to compare. I want to find the key and its value which is different in the second object. Which should return only the different key and its value in an object.

const obj1={name:"abc",age:21,place:"xyz"}
const obj2={name:"pqr",age:21}

So, here I want to return {name:"pqr"} as here the name value is different from the first object. And I have tried ,

const returnObject = Object.assign({}, findOwner, data);

and

const returnObject = { ...findOwner, ...data };

but these are returning not exactly what I want.

Advertisement

Answer

The solutions is,

function Newdifference(origObj, newObj) {
  function changes(newObj, origObj) {
    let arrayIndexCounter = 0
    return transform(newObj, function (result, value, key) {
      if (value && !isObject(value) && !isEqual(JSON.stringify(value), JSON.stringify(origObj[key]))) {
        let resultKey = isArray(origObj) ? arrayIndexCounter++ : key
        result[resultKey] = (isObject(value) && isObject(origObj[key])) ? changes(value, origObj[key]) : value
      }
    });
  };
  return changes(newObj, origObj);
}

This function will return the changes which are traced in two objects

Advertisement