Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda