0

我有对象数组,ob1ob2想检查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 []
4

3 回答 3

2

您可以通过filter使用 比较总数和获取信息总数来记录记录。这是一个工作示例qtyreduce()

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 result = ob1.filter(k=>k.total!=k.info.reduce((a, {qty})=>a+qty,0));

console.log(result);

我希望这将引导您朝着正确的方向前进。

于 2020-06-26T14:09:55.637 回答
1

我认为您正在寻找一个函数,该函数从对象的输入数组中返回对象的子集,其中 in 的总量total不等于qty内部对象中的量的总和info

您可以使用filter()获取不匹配对象的数组,检查总和的条件使用reduce()。下面是一个工作示例。

请注意,与您要求的不同,对第一个对象数组的调用返回一个包含罪魁祸首对象的数组,而不仅仅是对象本身。

function checkTotal(data) {
    return data.filter(({ total, info }) => (
        total !== info.reduce((acc, { qty }) => (acc + qty), 0)
    ));
}

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

console.log('ob1', checkTotal(ob1));
console.log('ob2', checkTotal(ob2));

于 2020-06-26T14:21:11.173 回答
1

工作评论示例:

// finds total sum of qtys in info array
function totalSum(infoArray) {
  return infoArray.reduce((acc, info) => acc + info.qty, 0);
}

// returns items with incorrect totals
function checkTotal(itemArray) {
  return itemArray.filter(item => item.total !== totalSum(item.info));
}

let ob1 = [
  {id:1, total:2, info:[{idx:1, qty:1}, {idx:2, qty:2}]}, // incorrect total
  {id:2, total:1, info:[{idx:1, qty:1}]}, // correct total
];

let ob2 = [
  {id:1, total:1, info:[{idx:1, qty:1}]}, // correct total
  {id:2, total:4, info:[{idx:1, qty:2}, {idx: 2, qty: 2}]}, // correct total
];

console.log(checkTotal(ob1)); // returns 1st item
console.log(checkTotal(ob2)); // returns empty array

于 2020-06-26T14:14:17.150 回答