jay dhawan
jay dhawan

Reputation: 67

Get total from json object

I have json of students

"students":{
    "ABC":{
        "eng": 25,
        "maths": 50,
        "sci": 25
    },
    "DEF": {
        "eng": 25,
        "maths": 48,
        "sci": 30
    }
}

I want to get the total marks per student.

Here is what I followed:

var marksCount = [];
$.each(response['students'], function(name, marksVal) {

    $.each(marksVal, function(index, val) {
        if (marksCount[name] == 'undefined') {
            marksCount[name] = 0;
            marksCount[name].push(val);
        }
    });
});

var studName = '', studMarks = 0;
$.each(marksCount, function(i, v)){
    studName = i;
    studMarks += i;
}


student name  total
ABC             100
DEF             103

Help I'm stuck.

Upvotes: 1

Views: 1853

Answers (3)

cнŝdk
cнŝdk

Reputation: 32145

First of all it's not a JSON object, there's no such a thing as a "JSON Object", it's nothing but a Javascript object.

But to answer your question, I want to get the total marks per student.:

You can simply do it using Object.keys(), Object.values(), Array#map() and Array#reduce() methods.

This is how should be your code:

var results = Object.keys(data.students).map(function(key) {
  let obj = {};
  obj[key] = Object.values(data.students[key]).reduce(function(a, b) {
    return a + b;
  });
  return obj;
});

Explanation:

The following code works like this:

  • We use Object.keys(data.students) to get all the keys (students names) from the studentsobject.
  • Then we loop over these keys with .map() method to return a custom object for each iterated key.
  • Then inside the .map() loop, for each key we get all the values of the object relative to this key (the marks values) with Object.values(data.students[key]).
  • And finally we use .reduce() method with the marks array taken from Object.values() call, and return a sum of these values.

Demo:

var data = {
  "students": {
    "ABC": {
      "eng": 25,
      "maths": 50,
      "sci": 25
    },
    "DEF": {
      "eng": 25,
      "maths": 48,
      "sci": 30
    }
  }
};

var results = Object.keys(data.students).map(function(key) {
  let obj = {};
  obj[key] = Object.values(data.students[key]).reduce(function(a, b) {
    return a + b;
  });
  return obj;
});

console.log(results);

Upvotes: 0

James Monger
James Monger

Reputation: 10665

You don't need to use jQuery to achieve this.

// a function to sum up an array of numbers
function sumValues(values) {
    return values.reduce(function (sum, value) {
        return sum + value;
    });
}

var students = {
    ABC: {
        eng: 25,
        maths: 50,
        sci: 25
    },
    DEF: {
        eng: 25,
        maths: 48,
        sci: 30
    }
};

// loop through all students in the list
Object.keys(students).forEach(function (studentName) {
    // get student details by name
    var student = students[studentName];

    // get all the grades for the student
    var grades = Object.values(student);

    // sum them up
    var total = sumValues(grades);

    console.log("Total for " + studentName + " is " + total);
});

You can achieve a lot without jQuery, and whenever you use it you should evaluate whether you're using it correctly. It's incredibly simple to sum up values with JavaScript alone, so you should do that.

Take a look at You Might Not Need jQuery for more examples of how to write the code you want without using jQuery.

Upvotes: 2

AJ -
AJ -

Reputation: 631

var students = {
ABC:{
    eng: 25,
    maths: 50,
    sci: 25
},
DEF: {
    eng: 25,
    maths: 48,
    sci: 30
}};
$.each(students, function(value, course) {
    console.log("Student: " + value);

    var sum = 0;
    $.each(course, function(grade, mark){
       sum += mark;
    })

    console.log("Sum: "+ sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

First you need to convert Json to Javascript object, after that you can apply below code:

var students = {
ABC:{
    eng: 25,
    maths: 50,
    sci: 25
},
DEF: {
    eng: 25,
    maths: 48,
    sci: 30
}};
$.each(students, function(value, course) {
    console.log("Student: " + value);

    var sum = 0;
    $.each(course, function(grade, mark){
       sum += mark;
    })

    console.log("Sum: "+ sum);
});

Upvotes: 0

Related Questions