我需要在数组中求和一些对象值。有些可以是int
,有些可以是string
,即:
JavaScript的:
let array = [
{quantity: 1, amount: "24.99"}
{quantity: 5, amount: "4.99"},
]
挖掘Stack Overflow我发现this method(我正在使用React):
Array.prototype.sum = function (prop) {
var total = 0
for ( var i = 0, _len = this.length; i < _len; i++ ) {
total += this[i][prop]
}
return total
};
let totalQuantity = array.sum("quantity");
console.log(totalQuantity);
虽然效果很好,但我需要对字符串amount
执行相同的操作。由于我需要将amount
转换为float,因此上述操作无效。 React抱怨Component's children should not be mutated.
不是JS忍者,我认为这会有些神奇:
Array.prototype.sum = function (prop) {
var newProp = parseFloat(prop);
var total = 0
for ( var i = 0, _len = this.length; i < _len; i++ ) {
total += this[i][newProp] // Surely this is wrong :(
}
return total
};
任何干净的方法来实现这一目标?
我需要这个:
let totalAmount = array.sum("amount");
答案 0 :(得分:4)
定义一个通用sum
函数,与
let sum = a => a.reduce((x, y) => x + y);
并将其应用于从源数组中选取的值列表:
let array = [
{quantity: 1, amount: "24.99"},
{quantity: 5, amount: "4.99"}
];
let sum = a => a.reduce((x, y) => x + y);
let totalAmount = sum(array.map(x => Number(x.amount)));
console.log(totalAmount.toFixed(2))
答案 1 :(得分:2)
请尝试:
Array.prototype.sum = function (prop) {
var total = 0
for ( var i = 0, _len = this.length; i < _len; i++ ) {
total += parseFloat(this[i][prop]) // Surely this will work :)
}
return total
};
答案 2 :(得分:0)
const array = [
{quantity: 1, amount: "24.99"},
{quantity: 5, amount: "4.99"}
]
Array.prototype.sum = function(key) {
return this.reduce(function(total, item) {
return total + parseFloat(item[key]);
}, 0);
}
// weird javascript math ...
console.log(array.sum("amount"));
// workaround
console.log(array.sum("amount").toFixed(2));
这项工作很好;)
答案 3 :(得分:0)
我经常使用reduce()
方法来处理这类情况。这是一个小小的演示:http://codepen.io/PiotrBerebecki/pen/zKEQgL
let array = [
{quantity: 1, amount: "24.99"},
{quantity: 5, amount: "4.99"}
]
function sumProperty(arr, type) {
return arr.reduce((total, obj) => {
if (typeof obj[type] === 'string') {
return total + Number(obj[type]);
}
return total + obj[type];
}, 0);
}
let totalAmount = ( sumProperty(array, 'amount') ).toFixed(2);
console.log( totalAmount ); // 29.98
let totalQuantity = sumProperty(array, 'quantity');
console.log( totalQuantity ); // 6