有效地求和不同的值

时间:2019-04-13 18:42:07

标签: javascript vue.js vuejs2

我得到了一个包含这样的对象的数组:

[
  {
    "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
  }
]

好的-现在,我想为以下项创建一个总和:

  • 设置(总计)
  • 价格(总计)
  • 所有产品的价格按时间间隔(按1,2,3,4,...分组)

现在我正在为每个任务使用计算值:

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;
},

但是这当然不是最佳选择,因为我不断地遍历数组。

所以我的问题是:如何创建一种更有效的方法来求和:

  • 总价
  • 价格(仅可选)
  • 设置总数
  • 设置(仅可选)
  • 按间隔价格

2 个答案:

答案 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.optionalcalcPrice.interval

希望您能明白。