繁体   English   中英

我有一个对象数组,每个对象内都有一个称为分数的键,我需要找到每个分数的总和并将其推入数组

[英]I have an array of objects, inside each object is key called scores, and I need to find the sum of each score and push it into an array

我的控制台向我显示了所有分数的总和,但是我希望它显示32和35而不是65。最终结果是我希望将每个总和压入一个数组。

 var peopleArray = [ { name: "Hector Valdes", photo: "", scores: [ "5", "1", "4", "4", "5", "1", "2", "5", "4", "1" ] }, { name: "Tyler Williams", photo: "", scores: [ "5", "1", "4", "4", "5", "2", "2", "5", "4", "1" ] } ] let total = 0; for (i = 0; i < peopleArray.length; i++){ for(j=0; j < peopleArray[i].scores.length; j++){ total += Number(peopleArray[i].scores[j]); console.log(total); }; }; 

 var peopleArray = [ { name: "Hector Valdes", photo: "", scores: [ "5", "1", "4", "4", "5", "1", "2", "5", "4", "1" ] }, { name: "Tyler Williams", photo: "", scores: [ "5", "1", "4", "4", "5", "2", "2", "5", "4", "1" ] } ] let total = peopleArray.map(i => { return i.scores.reduce((a, b) => parseInt(a) + parseInt(b), 0) }) console.log(total) 

您可以使用map遍历每个peopleArray元素。 使用reduce对分数求和。

通过在字符串前面加上+ ,可以将字符串转换为数字。

 var peopleArray = [{"name":"Hector Valdes","photo":"","scores":["5","1","4","4","5","1","2","5","4","1"]},{"name":"Tyler Williams","photo":"","scores":["5","1","4","4","5","2","2","5","4","1"]}]; var total = peopleArray.map(o => o.scores.reduce((c, v) => +c + +v)); console.log(total); 

尝试这个

const result = peopleArray.map((value) => {
    return {
        name: value.name,
        score: value.scores.reduce((total, score) => total + Number(score), 0)
    }

})
console.log(result);

尝试这个,

您需要在第一个循环中移动total ,然后只需要在数组中添加一个新的总计对象

var peopleArray = [
    {
        name: "Hector Valdes",
        photo: "",
        scores: [
            "5", "1", 
            "4", "4", 
            "5", "1", 
            "2", "5", 
            "4", "1" 
        ]
    }, {
        name: "Tyler Williams",
        photo: "",
        scores: [
            "5", "1",
            "4", "4",
            "5", "2",
            "2", "5",
            "4", "1"
        ]
    }
];
console.log(peopleArray);
for (i = 0; i < peopleArray.length; i++){
     let total = 0;
     for(j=0; j < peopleArray[i].scores.length; j++){
        total += Number(peopleArray[i].scores[j]);
     };
     peopleArray[i]['total'] = total;
     console.log(total);
};
console.log(peopleArray);

试试这个,希望对您有帮助。

let scoresArr = peopleArray.map(data => {   
return data.scores.reduce((a,b) => parseFloat(a) + parseFloat(b), 0) 
})

console.log(scoresArr)

暂无
暂无

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

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