Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
Comparing two objects if they have at least one value in common

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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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:

  1. for (const key in obj1): Loop through all the keys in the first object.
  2. if(obj1[key] === obj2[key]) return true: If the two objects agree on the value they have on one of these keys, return true immediately.
  3. return false: If you get through the entire loop without returning true, then they have nothing in common, and we return false.
about 4 years ago · Juan Pablo Isaza Relatório

0

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]);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda