1

I have a column in my Parse database populated with numbers and I'm trying to add them all together to get a total.

I know how to do the adding together if the data returned is a single array, but I can only figure out how to return the numbers as individual objects. This is my code which does that:

        var query = new Parse.Query(Services);
        query.exists("costMonthly");
        query.find({
            success: function (results) {
                for (var i = 0; i < results.length; i++) {
                    var object = results[i];
                    console.log(object.get('costMonthly'));
                }
            },
            error: function (error) {
                alert("Error: " + error.code + " " + error.message);
            }
        });

How would I go about fetching what I want as an array or at least converting what I have into one?

2 Answers 2

2

It looks like you are trying to sum the costMonthly field. You can use reduce to do this easily:

var query = new Parse.Query(Services);
query.exists("costMonthly");
query.find({
    success: function (results) {
        var sum = results.reduce(function(prev, cur) {
           return prev + cur.get('costMonthly');
        }, 0);
    },
    error: function (error) {
        alert("Error: " + error.code + " " + error.message);
    }
});

If your goal is an array of the costMonthly values, this will work:

var monthlyCosts = results.map(function(item) { 
   return item.get('costMonthly'); 
});

Read more about reduce here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

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

Comments

2

You can create a temporary array , and push results though through iteration , not the best solution , but is very useful if you want to manipulate results later :

var costMonthlyArray=[];
 var query = new Parse.Query(Services);
        query.exists("costMonthly");
        query.find({
            success: function (results) {
                for (var i = 0; i < results.length; i++) {
                    var object = results[i];
                    var cost=object.get('costMonthly');
                    costMonthlyArray.push(cost);
                    console.log(cost);
                }
            },
            error: function (error) {
                alert("Error: " + error.code + " " + error.message);
            }
        });

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.