Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

517
Views
JavaScript: ¿Cómo fusionar dos objetos pero mantener solo la propiedad del segundo objeto si existe?

Este código fusiona dos objetos. ¿Cómo modificarlo para que se descarte una propiedad del primer objeto si existe en el segundo objeto?

Por ejemplo, el objeto 1 tiene esta propiedad:

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

y objeto 2:

 surname: { test: '124' },

La combinación usaría la propiedad del objeto 2 ( other: '124' no existiría en el resultado combinado)

 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 answers
Answer question

0

Parece que desea hacer una fusión superficial pero con objetos recreados para evitar referencias a los originales.

Una forma rápida de hacerlo es usar Object.assign para la fusión, y luego hacer un json stringify / parse ( con las limitaciones de lo que admite JSON ) para clonar el resultado y perder las referencias ( alternativamente, podría structuredCloned si su entorno/ el navegador lo admite ).

Entonces algo como

 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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!