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
Post a Comment