获取属性列表已更改?

时间:2019-11-23 22:52:43

标签: javascript node.js

这是UpdateTotals的示例功能。

function updateTotals(data) {
    let grandTotal = 0;
    let totalTax = 0;

    data.Items.forEach(item => {
        const qty = parseInt(item.Qty, 10);
        const price = parseFloat(item.Price);
        const tax = parseFloat(item.Tax);

        const totalExc = price * qty;
        const totalInc = (price * qty) + tax;

        item.TotalExc = totalExc.toFixed(2);
        item.TotalInc = totalInc.toFixed(2);

        grandTotal += totalInc;
        totalTax += tax;
    });

    data.Totals.GrandTotal = grandTotal.toFixed(2);
    data.Totals.TotalTax = totalTax.toFixed(2);

    return data;
}

这只是一些已经重新计算了属性总和的示例,例如: data.Items[x].TotalExcdata.Items[x].TotalIncdata.Totals.GrandTotal

实际上,Items数组中的Items属性之外还有很多字段。

如何获取已更新的属性列表(总和),以便可以将这些属性传递给数据库(例如NoSQL)进行更新?

1 个答案:

答案 0 :(得分:2)

这是人为的,但是像这样……

const foo = {
  type: "fruit",
  name: "apple",
  color: "red"
};

const bar = {
  type: "fruit",
  name: "banana",
  color: "yellow"
};

function findChangedProps(prev, current) {
  const changedProps = [];

  for (const prop in prev) {
    if (prev[prop] !== current[prop]) {
      changedProps.push(prop);
    }
  }

  return changedProps;

}

console.log(findChangedProps(foo, bar));

如果您使用的是像React这样的库,它提供了嵌入式方法,但是,如果您仅使用Vanilla JS,则该AFAIK没有API。

----更新----

一些同事告诉我有关我不知道的新Proxy API的信息。这使您的函数可以创建要更新的代理对象。

var changedProps = [];

var foo = {
  type: "apple",
  color: "red"
};

var catcher = {
  set: function(obj, prop) {
    changedProps.push(prop);
    return Reflect.set(...arguments);
  }
};

var p = new Proxy(foo, catcher);

console.log("p before mutation", p);

p.color = "yellow";

console.log("p after mutation", p);

console.log("foo recieves mutation too", foo);

console.log("changedProps", changedProps);