简体   繁体   中英

I want to get the sum of data from array of the json object

I have the json data in array.


    var obj = [
        {
            student_data:{
                name: 'brj',
                id: '123',
                marks:[{'hi': 12, 'mt': 20, 'en': 20}]
            }
        },
        {
            student_data:{
                name: 'anand',
                id: '124',
                marks:[{'hi': 12, 'mt': 20, 'en': 20}]
            }
    
        }
    ]

here I want to add the marks and display the total, but i cant get it right because I'm unable to get the addition, here is the solution i tried.


    var i = 0;
    var t = 0;
    for(var i = 0; i<obj.length; i++){
        for(var j = 0; j<obj[i].student_data.marks[0].length; j++){
            t += obj[i].student_data.marks[0];
            //console.log(obj[i].student_data.marks[0])
            //console.log(t);
    
        };
        
    }

Expected output should be,

{ '123':{ name: 'bji', total_marks: 52 } }, { '124':{ name: 'anand', total_marks: 52 } }

obj[i].student_data.marks[0] is an object, you can't add it to a number.

You need to iterate through its values, which can be done using Object.values() .

 var obj = [{ student_data: { name: 'brj', id: '123', marks: [{ 'hi': 12, 'mt': 20, 'en': 20 }] } }, { student_data: { name: 'anand', id: '124', marks: [{ 'hi': 12, 'mt': 20, 'en': 20 }] } } ]; var t = 0; obj.forEach(o => o.student_data.marks.forEach(marks => Object.values(marks).forEach(mark => t += mark))); console.log(t);

You can use forEach to iterate over the appropriate arrays:

 var obj = [{ student_data: { name: 'brj', id: '123', marks: [{ 'hi': 12, 'mt': 20, 'en': 20 }] } }, { student_data: { name: 'anand', id: '124', marks: [{ 'hi': 12, 'mt': 20, 'en': 20 }] } } ] var sum = 0; obj.forEach(e => e.student_data.marks.forEach(f => Object.keys(f).forEach(g => sum += f[g]))); console.log(sum);

Although the two above are more efficient, you may wish to see it presented similar to your current code. Given your desired output:

var total = 0;
for(var i = 0; i < obj.length; i++){
    obj[i].student_data["total_marks"] = 0;
    for(var k in obj[i].student_data.marks[0]){
        obj[i].student_data["total_marks"] += obj[i].student_data.marks[0][k];
    };    
}
console.log(obj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM