我有以下数组:
const response = [{
name: "ISA Portfolio",
value: 0,
count: 1
},
{
name: "ISA Cash",
value: 0,
count: 1
},
{
name: "Bank 1 Year Fixed",
value: 149058.15234375,
count: 2
},
{
name: "1 Year Fixed",
value: 167488.0546875,
count: 2
},
{
name: "t Bank 1 Year Fixed",
value: 250223.4375,
count: 3
},
{
name: "M Bank 1 Year Fixed Term",
value: 149222.48828125,
count: 2
},
{
name: "Jr",
value: 768930.5625,
count: 1
},
{
name: "I Income Bond",
value: 400486.1875,
count: 3
},
{
name: "In 1 Year Fixed",
value: 83620.2734375,
count: 1
},
{
name: "I 3 Year Guaranteed Income Bond",
value: 140000,
count: 1
},
{
name: "I 1 Year Guaranteed Growth Bond",
value: 600000,
count: 2
},
{
name: "Co",
value: 46382.26171875,
count: 1
},
{
name: "Management",
value: 1113677,
count: 1
},
{
name: "Cs & Co",
value: 973906,
count: 1
},
{
name: "C Fund",
value: 82389.640625,
count: 1
},
{
name: "I 3 Year Guaranteed Growth Bond",
value: 250000,
count: 1
},
{
name: "S Saver",
value: 85194.953125,
count: 1
}
]
const sum = response.reduce(function(a, b) {
(a[b.value] ? a[b.value] += b.value : a[b.value] = b.value);
return a;
}, {});
console.log(sum);
,但这仅在对象中返回值,而不是总和。你能帮忙吗?谢谢
答案 0 :(得分:1)
只需先在.value
属性上进行映射,然后再将其缩小:
const response = [{
name: "ISA Portfolio",
value: 0,
count: 1
},
{
name: "ISA Cash",
value: 0,
count: 1
},
{
name: "Bank 1 Year Fixed",
value: 149058.15234375,
count: 2
},
{
name: "1 Year Fixed",
value: 167488.0546875,
count: 2
},
{
name: "t Bank 1 Year Fixed",
value: 250223.4375,
count: 3
},
{
name: "M Bank 1 Year Fixed Term",
value: 149222.48828125,
count: 2
},
{
name: "Jr",
value: 768930.5625,
count: 1
},
{
name: "I Income Bond",
value: 400486.1875,
count: 3
},
{
name: "In 1 Year Fixed",
value: 83620.2734375,
count: 1
},
{
name: "I 3 Year Guaranteed Income Bond",
value: 140000,
count: 1
},
{
name: "I 1 Year Guaranteed Growth Bond",
value: 600000,
count: 2
},
{
name: "Co",
value: 46382.26171875,
count: 1
},
{
name: "Management",
value: 1113677,
count: 1
},
{
name: "Cs & Co",
value: 973906,
count: 1
},
{
name: "C Fund",
value: 82389.640625,
count: 1
},
{
name: "I 3 Year Guaranteed Growth Bond",
value: 250000,
count: 1
},
{
name: "S Saver",
value: 85194.953125,
count: 1
}
]
const sum = response.map(x => x.value).reduce((a, b) => a + b);
console.log(sum);