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

122
Vistas
JS Object compare and get diff only

I have 2 objects.

The one object is Original Data.

const origin = { name: 'John', id: 'Doe', item: { drink: 'coffee', money: 0 } }

And the other object is Copied and Edited Data

const copied = { name: 'Alex', id: 'Doe', item: { drink: 'water', money: 0 } }

I would like to compare them and get diff only.

const out = compareObj(origin, copied);
console.log(out)
/*
{ name: 'Alex', item: { drink: 'water' } }
*/

How can I get this?

Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can recursively loop over the object and delete the non-duplicate properties from the copy object.

And if a property exists on the the original object and not on the copy, then add it into the copy object. Following part of the code does that:

if (!copy.hasOwnProperty(k)) {
  copy[k] = v;
}

function compare(original, copy) {
  for (let [k, v] of Object.entries(original)) {
    if (typeof v === "object" && v !== null) {
      if (!copy.hasOwnProperty(k)) {
        copy[k] = v;
      } else {
        compare(v, copy?.[k]);
      }
    } else {
      if (Object.is(v, copy?.[k])) {
        delete copy?.[k];
      }
    }
  }
  return copy;
}

const 
  original = { name: "John", id: "Doe", item: { drink: "coffee", money: 0, honey: 24 } },
  copy = { name: "Alex", id: "Doe", item: { drink: "water", money: 0 } },
  diff = compare(original, JSON.parse(JSON.stringify(copy)));

console.log(diff);

Note: You need to pass a clone of the copy object to the function since it mutates the passed copy object.

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