javascript - 如何将两个属性值相加,迭代对象的属性?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。那么我该怎么做才能实现我在这里需要的东西。如果有人可以帮助我,我将非常感激。
解决方案
您的 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 中通过许多其他方式实现相同的目标。
推荐阅读
- python - UnboundLocalError 当两个面出现在输入
- matlab - Matlab - 尝试高斯拟合的各种起点,选择具有最高 rsquare 的起点,然后绘制
- ocaml - 将项目附加到 Ocaml 中的列表时出现语法错误
- machine-learning - pyspark.sql.utils.IllegalArgumentException:'字段“功能”不存在
- python - 我有一个 N*M 字符矩阵,我试图在整个矩阵中找到最常见的字符,但它只计算最后一行
- python - 如何在加载增量训练的`tensorflow.keras.model`时强制执行特定的signature_map?
- swagger - 除登录外的所有 API 上的 Swagger 401
- r - 名称(x)中的 RStudioError <- 值:“名称”属性 [15] 必须与向量 [1] 的长度相同
- visual-studio - 这些是什么?(Visual Studio 文件名后的点或字母)
- amazon-web-services - 通过移动应用程序访问所有用户的 S3 PUT 存储桶