我有对象数组,ob1
我ob2
想检查total
每个对象的总量是否等于数组qty
中对象的总和info
。
如果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 []