简体   繁体   English

我想从 json 对象的数组中获取数据的总和

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

I have the json data in array.我有数组中的json数据。


    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. obj[i].student_data.marks[0]是一个对象,你不能把它加到一个数字上。

You need to iterate through its values, which can be done using Object.values() .您需要遍历它的值,这可以使用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:您可以使用forEach迭代适当的数组:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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