Given I have two objects, what is the simplest way to compare if they have at least one property matching (some or any)? I am not looking for a full match of a whole object A within object B but a match of partial object A within object B.
{
name: "John",
age: 23,
city: "London"
}
// and
{
name: "Craig",
age: 47,
city: "London"
}
// returns true
{
name: "Adrian",
age: 32,
city: "Sofia"
}
// and
{
name: "Tom",
age: 44,
city: "Oslo"
}
// returns false
I have tried several partial match functions by lodash (isMatch) but they seem to perform all-to-some or all-to-all matches, whereas I am looking for some-to-some.
CodePudding user response:
If you're simply checking if they have anything in common:
const john = { name: "John", age: 23, city: "London" }
const craig = { name: "Craig", age: 47, city: "London" }
const adrian = { name: "Adrian", age: 32, city: "Sofia" }
const tom = { name: "Tom", age: 44, city: "Oslo" }
function hasAnythingInCommon(obj1, obj2) {
for (const key in obj1) {
if(obj1[key] === obj2[key]) return true
}
return false
}
console.log(hasAnythingInCommon(john, craig))
console.log(hasAnythingInCommon(adrian, tom))
Short explanation:
for (const key in obj1)
: Loop through all the keys in the first object.if(obj1[key] === obj2[key]) return true
: If the two objects agree on the value they have on one of these keys, returntrue
immediately.return false
: If you get through the entire loop without returningtrue
, then they have nothing in common, and we returnfalse
.
CodePudding user response:
The easiest way is to simply list out all attributes as comparisons:
const compare = (a, b) => a.name === b.name || a.age === b.age || a.city === b.city;
A more generic version would be:
const compare = (a, b) => Object.entries(a).some(([key, value]) => value === b[key]);