1

I had the following json

var data = {
    "total": "",
    "scores": [{
        "subject": "maths",
        "marks": "50"
    }, {
        "subject": "science",
        "marks": "75"
    }]
};

Now in the total ,value should be 125 which should be updated automatically. Also in the scores keys ,the values will be coming dynamically.So all the marks should be added automatically and displayed in total. So how can I do this with any javascript . Can someone help me. Thanks!

Expected

var data = {
    "total": "125",
    "scores": [{
        "subject": "maths",
        "marks": "50"
    }, {
        "subject": "science",
        "marks": "75"
    }]
};
1
  • The only way is iteration. Iterate your array of objects and calculate Commented Sep 30, 2016 at 9:08

5 Answers 5

2

You can use reduce() to calculate total and then assign it to data.total

var data = {
  "total": "",
  "scores": [{
    "subject": "maths",
    "marks": "50"
  }, {
    "subject": "science",
    "marks": "75"
  }]
}

var total = data.scores.reduce(function(a, b) {
  return a + parseInt(b.marks);
}, 0)

data.total = total;
console.log(data)

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

1 Comment

this is not really dynamic.
1

You could apply a getter and reduce the values from scores.

var data = {
        get total() {
            return this.scores.reduce(function (r, a) { return r + +a.marks; }, 0)
        },
        scores: [{ subject: "maths", marks: "50" }, { subject: "science", marks: "75" }]
    };

console.log(data.total);

Comments

0

You can implement your own class:

function Data()
{
    this.scores = [];
    this.total = 0;

    this.addScore = function(subject ,marks) {
        var score = { "subject" : subject ,"marks" : marks };

        this.scores.push(score);
        this.total += marks;
    }

    this.stringify = function() {
        return JSON.stringify(this);
    }
}

var data = new Data();

data.addScore("maths",50);
console.log( data.stringify() );
data.addScore("science",75);
console.log( data.stringify() );

Output:

{"scores":[{"subject":"maths","marks":50}],"total":50}
{"scores":[{"subject":"maths","marks":50},{"subject":"science","marks":75}],"total":125}

You can use, object itself or the JSON string. Hope that helps...

Comments

0

A simple for loop should suffice.

let data = {
  "total": "",
  "scores": [{
    "subject": "maths",
    "marks": "50"
  }, {
    "subject": "science",
    "marks": "75"
  }]
};

for (let i in data.scores)
  data.total = ((parseInt(data.total) || 0) + parseInt(data.scores[i].marks)).toString();

console.log(data)

Comments

-1

Here is a ES 2015 Solution:

var result = 0;

for (let score of data.scores){
    result += parseInt(score.marks);
}

data.total = result;

And the same can be achieved with older JavaScript

result = 0;

for(var i = 0; i < data.scores.length; i++) {
    result += parseInt(data.scores[i].marks);
}

data.total = result;

You should able to fit this code snippets into your code. Just remember not to use for .. in, as it is deprecated due to https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Statements/for_each...in

Hope I could help

Edit: It seems that one some other MDM page about for .. in, that it is not stated as deprecated. So sorry about that.

4 Comments

Strange. The Site I got from MDM statet is as deprecated. Just wanted to include that, to make sure he doesn't use deprecated code, since I don't consider that good practice.
you were looking at for each ... in
I see. Didn't know there were 2 different for .. in in JavaScript (I'm usually using jQuery's for each). Thank you for telling me :)

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.