I have these three objects with a different number of values I need to check if available values are the same in other Object. Like if I compare obj1
with obj2
then in obj2
we have only two keys and in obj1
we have the same keys with the same values then it returns true
... Please help me to write the function
Thanks in advance:)
const obj1 = { age: 25, color: "white", weight: true };
const obj2 = { color: "white", weight: true }
const obj3 = { age: 26, color: "white", weight: true }
console.log(matches(obj1, obj2)); // true
console.log(matches(obj2, obj1)); // false
console.log(matches(obj3, obj1)); // false
console.log(matches(obj3, obj2)); // true
This is the solution:)
const obj1 = { age: 25, color: "white", weight: true };
const obj2 = { color: "white", weight: true }
const obj3 = { age: 26, color: "white", weight: true }
function matches(obj1, obj2) {
const isValidKeyValuePair = (currentKey) => {
return obj2[currentKey] === obj1[currentKey];
};
return Object.keys(obj2).every(isValidKeyValuePair)
}
console.log(matches(obj1, obj2)); // true
console.log(matches(obj2, obj1)); // false
console.log(matches(obj3, obj1)); // false
console.log(matches(obj3, obj2)); // true
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.