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

131
Vistas
Merge two JavaScript Objects, add numbers instead of replacing them

I would like to merge two objects together. Numbers should not be replaced, but added.

If I use the spread operator, numbers are replaced.

How it works for the moment:

let obj1 = { title: 'Number', num: 1 }
let obj2 = { title: 'Number', num: 2 }

let merge = { ...obj1, ...obj2 }
// Object { title: 'Number', num: 2 }

How it should work:

let obj1 = { title: 'Number', num: 1 }
let obj2 = { title: 'Number', num: 2 }

let merge = { ...obj1, ...obj2 }
// Object { title: 'Number', num: 3 }

In the end the number should be added to each other instead of being replaced. Is this possible with the spreach syntax?

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

0

You should be able to get the sum easily enough using Array.reduce(), we create an array containing the objects to be merged, then reduce to get the result:

let obj1 = { title: 'Number', num: 1 }
let obj2 = { title: 'Number', num: 2 }

let a = [obj1, obj2];

const result = a.reduce ((acc, cur) =>  { 
    return { ...cur, num: (acc.num || 0) + cur.num};
}, {});

console.log('Result:', result);
    
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Denunciar

0

You also can try something like this

    let obj1 = { title: 'Number', num: 1 }
    let obj2 = { title: 'Number', num: 2 }
  
    const obj = {};
    obj['title'] = obj1['title']
    obj['num'] = obj1['num'] + obj2['num']

    console.log(obj)
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