2

How would I go about adding all the values within the object?

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

This is my object:

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

What I want is to add the values to variables. Would I use split?

var a =
var b =
var c =
5
  • 2
    You just need three loops, one each for amountpay, amtpending and totalcost. From there you can convert the string values to numbers and add them up. split() is not appropriate in this case as that's for turning a string in to an array. Also note that your question has nothing to do with JSON nor AJAX, so I removed the references to them. Commented Jul 28, 2016 at 11:02
  • how do i do that... i know that it will count for each loop but i want to know the syntax Commented Jul 28, 2016 at 11:03
  • really not json? cause im catching these values through my ajax call to my php function which is returning print json_encode(variable); Commented Jul 28, 2016 at 11:06
  • Syntax: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Jul 28, 2016 at 11:06
  • @Marcos Pérez Gude what i meant was im not familiar with for loops in jquery certain syntax like hot do i get the count of the array in php i use count() Commented Jul 28, 2016 at 11:08

3 Answers 3

4

You can use Array.prototype.reduce() as shown below:

var obj = {
    "amoutpay": [ "4222", "1000" ],
    "amtpending": [ "778", "4000" ],
    "totalcost": [ "5000", "5000" ],
    "coursename": [ "Office Automation", "ajaba" ]
},
    
    a = 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 you could go a step further and define your 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 a = obj.amoutpay.sum(),
    b = obj.amtpending.sum(),
    c = obj.totalcost.sum();

console.log( a, b, c );

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks That Helped
btw ind what value is that grabbing? i dont see any use of it inside the function
That's the current index. In this particular instance it's not required; you can safely leave it out. I just included it to show what parameters are passed - I know I should have said something about it, and you just gave me a chance to. Hope that helps :)
2
var obj = {
    "amoutpay": [ "4222", "1000" ],
    "amtpending": [ "778", "4000" ],
    "totalcost": [ "5000", "5000" ],
    "coursename": [ "Office Automation", "ajaba" ]
}

var a = addValues(obj.amoutpay);

function addValues(arr) {
    return arr.map(function(el) {
        return Number(el);
    }).reduce(function(prev, curr){
        return prev + curr;
    })
}

Comments

1

We iterate the object elements and for all arrays we check whether all the elements are numeric. If so, then add them as variables to the window object, so after the loop we will have an amoutpay variable for the input shown in the question. Note, that if a key happens to already be a variable, then this code will override it.

for (var key in obj) {
    if (Array.isArray(obj[key])) {
        var shouldAdd = true;
        for (var index = 0; shouldAdd && index < obj[key].length; index++) {
            if (isNaN(obj[key][index])) {
                shouldAdd = false;
            }
        }
        if (shouldAdd) {
            window[key] = 0;
            for (var index = 0; index < obj[key].length; index++) {
                window[key] += parseFloat(obj[key][index]);
            }
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.