0

I want to check if two JSON objects are same in Typescript(Angular), ignoring some key value pairs which may be optional.

obj1 = {name: 'Anna', password: 'test123', status: 'active'}
obj2 = {name: 'Anna', password: 'test123'}

Technically 'status' is optional, so I want the comparison to return true only considering first two properties. How to check this?

0

2 Answers 2

3

You could:

  • Get common keys of obj1 and obj2 (with a set)
  • Compare each key one-to-one
function compare(obj1, obj2) {
  const commonKeys = [...new Set([...Object.keys(obj1), ...Object.keys(obj2)])];

  for (const key of commonKeys) {
    if (obj1[key] !== obj2[key]) {
      return false;
    }
  }

  return true;
}
Sign up to request clarification or add additional context in comments.

Comments

1

try this

 Boolean theSame= obj1.name==obj2.name && obj1.password==obj2.password;

Comments

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.