我得到了一个包含这样的对象的数组:
[
{
"id": 91,
"factor": 2,
"title": "Test Product",
"price": 50,
"interval": 1,
"setup": 0,
"optional": false
},
{
"id": 92,
"factor": 1,
"title": "Another Test Product",
"price": 95,
"interval": 1,
"setup": 99,
"optional": true
},
{
"id": 93,
"factor": 1,
"title": "Just Another Test Product",
"price": 12,
"interval": 1,
"setup": 0,
"optional": false
}
]
好的-现在,我想为以下项创建一个总和:
现在我正在为每个任务使用计算值:
setupTotal: function () {
return this.products.reduce ((acc, product) => acc + (parseFloat (product.setup) * parseFloat (product.factor)), 0);
},
和
monthlyCostsTotal: function () {
let sum = 0;
this.products.forEach (function (product) {
if (product.interval == 1) {
sum += (parseFloat (product.price) * parseFloat (product.factor));
}
});
return sum;
},
和
setupOptional: function () {
let sum = 0;
this.products.forEach (function (product) {
if (product.optional) {
sum += (parseFloat (product.setup) * parseFloat (product.factor));
}
});
return sum;
},
但是这当然不是最佳选择,因为我不断地遍历数组。
所以我的问题是:如何创建一种更有效的方法来求和:
答案 0 :(得分:1)
您可以根据需要带一个对象并求和。
var data = [{ id: 91, factor: 2, title: "Test Product", price: 50, interval: 1, setup: 0, optional: false }, { id: 92, factor: 1, title: "Another Test Product", price: 95, interval: 1, setup: 99, optional: true }, { id: 93, factor: 1, title: "Just Another Test Product", price: 12, interval: 1, setup: 0, optional: false }],
result = data.reduce((r, { factor, price, interval, setup, optional }) => {
r.price += factor * price;
r.setup += factor * setup;
if (optional) {
r.price_optional += factor * price;
r.setup_optional += factor * setup;
}
r.interval[interval] = (r.interval[interval] || 0) + factor * price;
return r;
}, { price: 0, price_optional: 0, setup: 0, setup_optional: 0, interval: {} });
console.log(result);
答案 1 :(得分:1)
您可以使用一个计算函数并返回一个包含结果的对象:
calcPrice: function () {
let optional_sum = 0;
let interval_sum = 0;
this.products.forEach (function (product) {
if (product.optional) {
optional_sum += (parseFloat (product.setup) * parseFloat (product.factor));
}
if (product.interval == 1) {
interval_sum += (parseFloat (product.price) * parseFloat (product.factor));
}
});
return {
optional : optional_sum ,
interval : interval_sum
}
};
然后您可以使用它,例如:calcPrice.optional
或calcPrice.interval
希望您能明白。