H Varma
H Varma

Reputation: 630

How to add two key values and display in another keyvalue dynamically in json using javascript

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"
    }]
};

Upvotes: 1

Views: 60

Answers (5)

Jonathan Nielsen
Jonathan Nielsen

Reputation: 1502

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)

Upvotes: 0

JHolub
JHolub

Reputation: 300

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.

Upvotes: -1

Kartal
Kartal

Reputation: 444

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...

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122087

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)

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386726

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);

Upvotes: 1

Related Questions