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?
CodePudding user response:
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;
}
CodePudding user response:
try this
Boolean theSame= obj1.name==obj2.name && obj1.password==obj2.password;