Xoana
Xoana

Reputation: 3

Compare typescript objects and add diff to new object

Within my Angular application, I need to compare two typescript objects and create a new object that consists of key/value pairs where the value of the key is different in the second object.

Here is my code:

const objBefore = {id: 100088, firstName: "Joe", lastName: "Smith", notes: null};
const objAfter = {id: 100088, firstName: "John", lastName: "Johnson", notes: null};

let newObj = {};

for(let key in objBefore) {
    if (objBefore[key] !== objAfter[key]) {

        let newEntry = { key:  objAfter[key]}
        Object.assign(newObj, newEntry)
    }
}

console.log(newObj)

The output is:

{ key: 'Johnson' }

I need the output to be:

{ firstName: "John", lastName: "Johnson" }

How do I assign the value of the key (e.g., firstName) instead of the variable (key)?

Upvotes: 0

Views: 128

Answers (1)

Aadmaa
Aadmaa

Reputation: 932

Just use square brackets on [key]

const objBefore = {id: 100088, firstName: "Joe", lastName: "Smith", notes: null};
const objAfter = {id: 100088, firstName: "John", lastName: "Johnson", notes: null};

let newObj = {};

for(let key in objBefore) {
    if (objBefore[key] !== objAfter[key]) {

        let newEntry = { [key]:  objAfter[key]}
        Object.assign(newObj, newEntry)
    }
}

Upvotes: 1

Related Questions