-3

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.

  • What have tried? Add any attempts you've made to solve this issue. – Dane Brouwer Apr 29 '21 at 08:15
  • 2
    Here's the first result of a google search for your question title: https://stackoverflow.com/questions/8572826/generic-deep-diff-between-two-objects –  Apr 29 '21 at 08:18
  • 1
    Please add your inputs, expected output and the code you've tried. There are plenty of similar questions incuding nested objects: [Compare nested objects in JavaScript and return keys equality](https://stackoverflow.com/questions/55591096) and [Get the property of the difference between two objects in javascript](https://stackoverflow.com/questions/46930387) – adiga Apr 29 '21 at 08:18
  • Please read [tour] _"Don't ask about... Questions you haven't tried to find an answer for (show your work!)"_ –  Apr 29 '21 at 08:31
  • 1
    You can see the changes in the question – Saichandhra Arvapally Apr 29 '21 at 09:36

2 Answers2

0

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

0

I found better way to compare any count of type with any property order:

let isEqual = (...params) => params.map(Object.keys).reduce((prev, cur) => [...prev, ...cur], []).every(key => params.every(param => param[key] === params[0][key]))

example

slava guk
  • 1
  • 1