javascript - Adding values contained in an array of objects -


how go adding values within object?

for example amoutpay": ["4222","1000"] give me 5222

this object:

{     "amoutpay": [ "4222", "1000" ],     "amtpending": [ "778", "4000" ],     "totalcost": [ "5000", "5000" ],     "coursename": [ "office automation", "ajaba" ] } 

what want add values variables. use split?

var = var b = var c = 

you can use array.prototype.reduce() shown below:

var obj = {      "amoutpay": [ "4222", "1000" ],      "amtpending": [ "778", "4000" ],      "totalcost": [ "5000", "5000" ],      "coursename": [ "office automation", "ajaba" ]  },            = obj.amoutpay.reduce(function(prevval, curval, curind) {          return +prevval + +curval;      }),      b = obj.amtpending.reduce(function(prevval, curval, curind) {          return +prevval + +curval;      }),      c = obj.totalcost.reduce(function(prevval, curval, curind) {          return +prevval + +curval;      });    console.log( a, b, c );

or go step further , define own array method, eg array.prototype.sum():

var obj = {          "amoutpay": [ "4222", "1000" ],          "amtpending": [ "778", "4000" ],          "totalcost": [ "5000", "5000" ],          "coursename": [ "office automation", "ajaba" ]      };    array.prototype.sum = function() {      return this.reduce(function( prv, cur, ind ) {          return +prv + +cur;      });  };    var = obj.amoutpay.sum(),      b = obj.amtpending.sum(),      c = obj.totalcost.sum();    console.log( a, b, c );


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -