Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

168
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda