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

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

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 Report

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 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!