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

513
Vistas
JavaScript: How to merge two object but keep only the property of the second object if it exists?

This code merges two objects. How to amend it so that a property is discarded of the first object if it exists in the second object?

E.g. object 1 has this property:

surname: {
    test: '123',
    other: '124'
},

and object 2:

surname: {
    test: '124'
},

The merge would use the property of object 2 (other: '124' would not exist in the merged result)

function merge(...objects) {
    function m(t, s) {
        Object.entries(s).forEach(([k, v]) => {
            t[k] = v && typeof v === 'object' ? m(t[k] || {}, v) : v;
        });
        return t;
    }

    return objects.reduce(m, {});
}

var obj1 = {
        name: '112',
        surname: {
            test: '123',
            other: '124'
        },
        age: 151,
        height: '183',
        weight: 80
    },
    
    obj2 = {
        name: '114',
        surname: {
            test: '124'
        },
        age: 151,
        height: 184,
        weight: 81
    },
    
    result = merge(obj1, obj2);

console.log(result);

about 4 years ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

You seem to want to do a shallow merge but with recreated objects to avoid references to the original ones.

A quick way for this is to use Object.assign for the merge, and then do a json stringify/parse (with the limitations of what JSON supports) to clone the result and lose the references (you could alternatively use structuredCloned if your environment/browser supports it).

So something like

function merge(...objects) {
  const shallowClone = Object.assign({}, ...objects);
  const asString = JSON.stringify(shallowClone);
  const asObject = JSON.parse(asString);
  return asObject;
}
about 4 years ago · Santiago Gelvez Denunciar

0

const a = { x:1, y:2}
const b = { x:5 }
const c = { ...a, ...b }
console.log(c)
// Answer will be {x: 5, y: 2}
about 4 years ago · Santiago Gelvez 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