Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum values of two different objects

I have two different objects

var objA = { a: 10, b: 20, c: 30 }; var objB = { a: 3, c: 6, d: 3 };

and I want to sum their values , like in this example below

{ a: 13, b: 20, c: 36, d: 3 }
like image 837
Duca Avatar asked Dec 08 '22 19:12

Duca


2 Answers

Use Array#reduce method

var objA = {
  a: 10,
  b: 20,
  c: 30
};
var objB = {
  a: 3,
  c: 6,
  d: 3
};

console.log(
  // concatenate keys array
  Object.keys(objA).concat(Object.keys(objB))
  // or use Object.keys(Object.assign({},objA,objB))

  // iterate to generate the object
  .reduce(function(obj, k) {
    // define object property, treat as 0 if not defined
    obj[k] = (objA[k] || 0) + (objB[k] || 0);
    // return object difference
    return obj;
    // set initial value as an empty object
  }, {})
)

Or much better way by defining initial value as the copy of second object.

var objA = {
  a: 10,
  b: 20,
  c: 30
};
var objB = {
  a: 3,
  c: 6,
  d: 3
};

console.log(
  // get property names array of objB ----Edit objA -----
  Object.keys(objA)
  // iterate over array
  .reduce(function(obj, k) {
    // add value to existing property or update
    obj[k] = (obj[k] || 0) + objA[k];
    // return object reference
    return obj;
    // define initial value as an object which holds 
    // all the property and value in objB
  }, Object.assign({}, objB))
)
like image 68
Pranav C Balan Avatar answered Dec 10 '22 07:12

Pranav C Balan


Using lodash

function customizer(objValue, srcValue) {
    if(objValue && srcValue)
    return objValue+srcValue;
}

var objA = { a: 10, b: 20, c: 30 }; var objB = { a: 3, c: 6, d: 3 };

console.log(_.mergeWith(objA, objB, customizer));

Demo

like image 38
AshBringer Avatar answered Dec 10 '22 07:12

AshBringer