-3
var obj1={
  name:"jhon",
  age:"26",
  role:"intern"
}

var obj2={
  name:"jhon berner",
  age:"26",
  role:"intern"
}

//so the name value has changed in the above object so I need new object like

expected output

var newobj={
name:"jhon berner"
}

// can I do like this for objects

shashank
  • 15
  • 5
  • 2
    Does this answer your question? [Generic deep diff between two objects](https://stackoverflow.com/questions/8572826/generic-deep-diff-between-two-objects) – pilchard Jul 18 '22 at 07:44
  • also: [JavaScript - Return differences between two Objects?](https://stackoverflow.com/questions/57899882/javascript-return-differences-between-two-objects) – pilchard Jul 18 '22 at 07:46

1 Answers1

-1

I was not sure which value you wanted as an output for different keys, so I added both different values in an array... you can modify it based on your requirement.

Assumption: keys present in both objects are the same.

var obj1 = { name: 'jhon', age: '26', role: 'intern' };
var obj2 = { name: 'jhon berner', age: '26', role: 'intern' };
var newObj = {};
Object.keys(obj1).forEach((key) => {
    if (obj1[key] !== obj2[key]) {
        newObj[key] = [obj1[key], obj2[key]];
    }
});

console.log(newObj);
RKataria
  • 581
  • 1
  • 5
  • 12
  • 2
    This is a duplicate multiple times over. Just flag to close. Also this only iterates the keys of the first object, so if obj2 has more properties they won't be included in the diff. – pilchard Jul 18 '22 at 07:46