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

170
Visualizações
How do I filter only common object values in Javascript

I want to filter out key value pairs which are common in both objects. There are two objects:

first = {a:3 , b:4}
second  = {a:5 , b:4}

I used the below code to solve this:

c = {}
for (const key of Object.keys(first)) {
    for( const k of Object.keys(second)){
        if ( key == k){
            if (first[key]==second[k]){
                c[key] = first[key]
            }
        }
    }
}

This works fine and gives me the output {b:4}, but for the below test input values I get empty object as the output, I am not sure how to check for values that are common but not equal.

first = {a: 3, b: {x:7}};
second = {a: 4, b: {x: 7, y: 10}}

Here the output should be:

{b: {x:7}}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could take a recursive approach for nested objects and check for common keys and common values or if both values are objects take the common values of the nested objects.

function getCommon(a, b) {
    const isObject = o => typeof o === 'object';

    return Object.fromEntries(Object
        .keys(a)
        .filter(Set.prototype.has, new Set(Object.keys(b)))
        .filter(k => a[k] === b[k] || isObject(a[k]) && isObject(b[k]))
        .map(k => [k, isObject(a[k]) ? getCommon(a[k], b[k]) : a[k]])
    );
}

console.log(getCommon({ a: 3, b: { x: 7 } }, { a: 4, b: { x: 7, y: 10 } }));

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