首页 > 解决方案 > 如何将两个属性值相加,迭代对象的属性?js

问题描述

我有这个对象,其中每个属性都有一个数组作为值,并且在另一个对象内部:

  products: {
        product1Options: [{ itemName: "", itemRate: 0, itemAmount: 0 }],
        product2Options: [{ itemName: "", itemRate: 0, itemAmount: 0 }],
        product3Options: [{ itemName: "", itemRate: 0, itemAmount: 0 }],
        },

在某些输入中,我更改了 0 的值,我需要将每个数组内每个对象中的 itemRate 和 itemAmount 相乘。所以我做了这个:

 if (this.products.product1Options.length ||
            this.products.product2Options.length ||
            this.products.product3Options.length) {

            for(let prop in this.products) {
                prop.map((obj) => {
                     
                if(obj.itemRate > 0 && obj.itemAmount > 0 ) {
                    let sum = 0;
                    return sum += prop.itemRate * prop.itemAmount;
                }
                })
            }; }

但我得到 prop.map 不是一个函数,我意识到那是因为 prop 实际上是一个对象 prop。那么我该怎么做才能实现我在这里需要的东西。如果有人可以帮助我,我将非常感激。

标签: javascriptarraysobject

解决方案


您的 for..in 循环迭代对象的属性而不是其值。所以在你的循环里面,prop只是一个字符串。你可以做

for(let prop in this.products) {
  this.products[prop].map((obj) => {
    if(obj.itemRate > 0 && obj.itemAmount > 0 ) {
      let sum = 0;
      return sum += prop.itemRate * prop.itemAmount;
    }
  })
 };

或者

for(let prop in Object.values(this.products)) {
  // .map returns an array but you are not doing anything with it
  prop.map((obj) => {
    if(obj.itemRate > 0 && obj.itemAmount > 0 ) {
      let sum = 0; // This var is not helping since it gets reset to 0 every time
      return sum += prop.itemRate * prop.itemAmount;
    }
    // when you get here you don't return anything
  })
 };

但是,您似乎并没有正确使用 map 函数,有时您会在不满足条件undefined时返回。if而且您实际上并没有对映射返回的数组做任何事情。如果您关心的是每个产品的总和,您可以在循环之外声明 sum 或者使用reduce

for (let prop in this.products) {
  const sum = this.products[prop].reduce((acc, item) => {
    if (item.itemRate > 0 && item.itemAmount > 0) {
      return acc + item.itemRate * item.itemAmount;
    }
    return acc;
  }, 0);
  // do something with sum
}

老实说,尽管该if检查似乎没有那么有用,因为如果它们都是 0,则您只需将 0 添加到总和中。所以你可以像这样简化:

for (let prop in this.products) {
  // If you are not familiar with reduce go check it out! What we do here
  // is reducing an array to a single value. We initialize it with 0 and for
  // each item in the array we add the rate * amount to the previous sum
  const sum = this.products[prop].reduce((prevSum, item) => prevSum + item.itemRate * item.itemAmount, 0);
}

然后我假设你用这笔钱做点什么。如果你想要最终的总数,你会得到这样的东西:

let totalSum = 0;
for (let prop in this.products) {
  totalSum += this.products[prop].reduce((prevSum, item) => prevSum + item.itemRate * item.itemAmount, 0);
}

从技术上讲,您可以更进一步,只需一次减少即可完成所有操作,但我会让您弄清楚这一点。请记住,可读性很重要!如果你不喜欢 reduce,不要觉得你必须使用它,我只是想向你展示什么是可能的,但你可以在 JS 中通过许多其他方式实现相同的目标。


推荐阅读