Home > Enterprise >  How compare two objects in javascript and create new object whose values are diffrent
How compare two objects in javascript and create new object whose values are diffrent

Time:07-25

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

CodePudding user response:

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);

  • Related