我如何通过一个对象的属性迭代两个属性值求和?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;
}
})
}; }

但我得到道具。Map不是一个函数,我意识到这是因为prop实际上是一个对象。那么我怎样才能达到我在这里所需要的呢?如果有人能帮助我,我将非常感激。

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

但它似乎也没有正确使用映射函数,有时当if条件不满足时,您将返回undefined。你并没有对映射返回的数组做任何事情。如果你关心的是每个乘积的和你可以在循环外声明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中以许多其他方式实现相同的目标。

最新更新