Ich muss einige Objektwerte in einem Array summieren. Einige können int
sein, während andere sein kann string
dh:Summe der String-Werte auf Array-Objekt
JavaScript:
let array = [
{quantity: 1, amount: "24.99"}
{quantity: 5, amount: "4.99"},
]
Graben um Stack-Überlauf I this method gefunden haben (Im Reagieren mit):
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);
Während das Arbeiten Toll, ich muss das gleiche für die Zeichenfolge amount
tun. Da ich amount
in Float konvertieren muss, wird das obige nicht funktionieren. Reagieren Sie beschwert sich über Component's children should not be mutated.
Nicht ninja sein JS, dachte ich, das etwas Magie tun würde:
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
};
jede saubere Art und Weise, dies zu erreichen?
Ich brauche dies:
let totalAmount = array.sum("amount");
Guter Fang. Ich habe mich gefragt, ob es einen anderen Weg gibt, anstatt 'Array.prototype' zu verwenden – Sylar