【发布时间】:2020-10-17 03:49:08
【问题描述】:
我有对象数组ob1 和ob2,我想检查每个对象的总量total 是否等于info 中对象的qtys 的总和数组。
如果所有对象的total = sum(info.qty) 则返回一个空数组,否则返回具有无效total 字段的对象。
到目前为止我的尝试:
function checktotal(ob1) {
var result = ob1.forEach(e => {
if (e.info.length > 0) {
var sum = e.info.reduce((a, {qty}) => a + qty, 0);
if (sum !== e.total) {
return "total qty not matches with info total qty,"+e
}
})
}
var ob1 = [
{id:1, total: 2, info:[{idx:1, qty:1},{idx: 2, qty: 2}] },
{id:2, total:1, info: [{idx:1, qty:1}] };
];
var ob2 = [
{id:1, total: 1, info:[{idx:1, qty:1}] },
{id:2, total:4, info: [{idx:1, qty:2},{idx: 2, qty: 2}] };
];
预期输出:
checktotal(ob1); // should return [{id:1, total:2, info:[{idx:1, qty:1}, {idx:2, qty:2}]}]
checktotal(ob2); // should return []
【问题讨论】:
-
.forEach()不返回任何内容。 -
如果多个条目与
total值不匹配会怎样?ob1[1].total === 2会是什么结果? -
您的代码中有几个语法错误,可能来自复制和粘贴。例如,
if(e.info.length > 0) {块缺少结束括号}。如果您使用Stack Snippets 创建了minimal reproducible example(图标在编辑器工具栏中的页面中类似于<>),使用console.log显示结果,然后单击运行以确保没有错误,这将很有帮助。
标签: javascript arrays object nested-object