如何对对象数组中的特定选项求和?

时间:2019-01-29 17:06:14

标签: javascript

我有这个数组:

[
   { id: "1", option { points: "1"} },
   { id: "2", option { points: "20"} },
   { id: "3", option { points: "4"} },
]

我试图对所有具有属性option的对象points求和,所以我这样做了:

 var total_points = this.my_arr.reduce(function(a, b){
        return a + b.option.points;
    }, 0);

但是这将返回每个id的索引的连接,例如:012,这当然是错误的。

预期输出为:25

4 个答案:

答案 0 :(得分:3)

您必须将字符串转换为数字,例如:

var total_points = this.my_arr.reduce(function(a, b){
    return a + parseInt(b.option.points);
}, 0);

答案 1 :(得分:1)

更正您的对象并将b强制转换为Number。在对象中,值是字符串,因此当+与字符串concatenations一起使用时,不会发生加法运算。这就是将strings转换为numbers然后添加的原因

var e=[
   { id: "1", option :{ points: "1"} },
   { id: "2", option :{ points: "20"} },
   { id: "3", option :{ points: "4"} },
]


 var total_points = e.reduce(function(a, b){
        return a + Number(b.option.points);
    }, 0);
    console.log(total_points);

答案 2 :(得分:1)

当您使用string运算符b / w两个+时,在对象中的选项为strings,然后将两者合并。使用parseInt()Number()

将字符串转换为数字
var total_points = this.my_arr.reduce(function(a, b){
        return a + parseInt(b.option.points);
    }, 0);

答案 3 :(得分:1)

您必须将字符串转换为数字,可以使用parseInt,或者甚至更简单地在字符串前加上+

此版本可用于 NaN 未定义缺少属性

const data = [
   { id: "1", option: { points: "1" } },
   { id: "2", option: { points: "20" } },
   { id: "3", option: { points: "4" } },
   { id: "4", option: { points: NaN } },
   { id: "5", option: { points: undefined } },
   { id: "6", option: { } },
   { id: "7" },
];

const totalPoints = data.reduce((accum, elem) => {
  const value = elem.option && elem.option.points ? +elem.option.points : 0;
  return accum + value;
}, 0);

console.log(totalPoints);