1

我有一个对象obj,其中如何删除重复项info并将数量的总和应用于javascriptqty中的键total。如何删除数组对象中的重复项并将 sum 应用于 javascript 中的特定键。

function newList (obj){
 return obj.map(i=>({
          ...i,
          total: i.info.map(e => e.qty).reduce((prev, curr) => prev + curr, 0)
 }));
}

var obj =[
 {id:1, info:[{idx:1, qty: 1}, {idx:2, qty: 2},{idx:2, qty: 2}], code: "sample1", total: 1},
 {id:2, info:[{idx:3, qty: 2}, {idx:4, qty: 2}], code: "sample2", total: 2}
]

预期输出:

[
 {id:1, info:[{idx:1, qty: 1}, {idx:2, qty: 2}], code: "sample1", total: 3},
 {id:2, info:[{idx:3, qty: 2}, {idx:4, qty: 2}], code: "sample2", total: 4}
]
4

3 回答 3

0

您可以使用reduceand Map(唯一的行):

var obj =[
 {id:1, info:[{idx:1, qty: 1}, {idx:2, qty: 2},{idx:2, qty: 2}], code: "sample1", total: 1},
 {id:2, info:[{idx:3, qty: 2}, {idx:4, qty: 2}], code: "sample2", total: 2}
];

var result = obj.reduce((acc, elem)=>{
    elem.info = [...new Map(elem.info.map(i=>[i.idx, i])).values()];
    elem.total = elem.info.reduce((sum, {qty})=>sum+qty,0);
    acc = [...acc, elem];
    return acc;
},[]);

console.log(result);

于 2020-06-28T13:41:52.777 回答
0

请尝试以下示例,尽管我的结果与显示为预期结果的总数不同。请试一试

const obj = [
  {
    id: 1,
    info: [
      { idx: 1, qty: 1 },
      { idx: 2, qty: 2 },
      { idx: 2, qty: 2 },
    ],
    code: "sample1",
    total: 1,
  },
  {
    id: 2,
    info: [
      { idx: 3, qty: 2 },
      { idx: 4, qty: 2 },
    ],
    code: "sample2",
    total: 2,
  },
];

let output = obj.map((entry) => {
  return {
    ...entry,
    info: entry.info.reduce((prev, curr) => {
      const item = prev.find(
        (element) => element.idx === curr.idx && element.qty == curr.qty
      );

      if (!item) {
        prev = [...prev, curr];
      }

      return prev;
    }, []),
  };
});

output = output.map((entry) => {
  return {
    ...entry,
    total: entry.total + entry.info.reduce((prev, curr) => prev + curr.qty, 0),
  };
});

console.dir(output, { depth: null, color: true });

于 2020-06-28T13:50:03.543 回答
0
function newList(obj) {
    return obj.map(i => ({
        ...i,
        ...reduceInfo(i.info)
    }));

}

function reduceInfo(array) {
    return array.reduce((a, c) => {
        a.info = a.info || [];
        a.total = a.total || 0;
        if (!a.info.some(element => c.idx === element.idx && c.qty === element.qty)) {
            a.info.push(c);
            a.total = a.total + c.qty;
        }
        return a;

    }, {});
}

var obj = [
    { id: 1, info: [{ idx: 1, qty: 1 }, { idx: 2, qty: 2 }, { idx: 2, qty: 2 }], code: "sample1", total: 1 },
    { id: 2, info: [{ idx: 3, qty: 2 }, { idx: 4, qty: 2 }], code: "sample2", total: 2 }
]

console.log(JSON.stringify(newList(obj)));
于 2020-06-28T14:09:54.453 回答