-2
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

2

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.