0

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

1 Answer 1

1

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)
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow! I've been trying to figure this out for hours! Thank you for the quick response!

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.