我编写了一个逻辑,以合并message2变量中的所有批次。如果存在重复的批次名称(AA,BB),它将合并所有批次并计算行数。

var message2 = {
    Batches: [
        {Batch: "AA", Lines: 1 },
        {Batch: "BB", Lines: 2 },
        {Batch: "BB", Lines: 6 }
    ]
}


成为:

[ { Batch: 'AA', Lines: 1 }, { Batch: 'BB', Lines: 8 } ]


这是通过reduce()方法完成的。

forEach循环中,它将循环所有mergedBatches(合并后),并与Worker变量中的批次进行比较。如果Worker行多于mergedBatches行,然后将mergedBatches设置为与Worker行匹配,则它将需要找到相同的批次名称。

var message2 = {
    Batches: [
        {Batch: "AA", Lines: 1 },
        {Batch: "BB", Lines: 2 },
        {Batch: "BB", Lines: 6 }
    ]
}

var Worker = {
    Batches: [
        {Batch: "AA", Lines: 2 },
        {Batch: "BB", Lines: 3 },
    ]
}

var mergedBatches = message2.Batches.reduce((acc, obj)=>{
    var existObj = acc.find(b => b.Batch === obj.Batch);

    if(existObj) {
      existObj.Lines += obj.Lines;
      return acc;
    }

    acc.push({Batch: obj.Batch, Lines: obj.Lines});
    return acc;
},[]);

mergedBatches.forEach((b) => {
    var workerBatch = Worker.Batches.find(wB => wB.Batch === b.Batch);
    if (b.Lines >= workerBatch.Lines) {
        b.Lines = workerBatch.Lines;
    }
});


console.log(mergedBatches)


最终结果按预期工作:

[ { Batch: 'AA', Lines: 1 }, { Batch: 'BB', Lines: 3 } ]


有没有一种方法可以重构此代码以使其更具可读性或更好的方法?

最佳答案

这是一个简短的版本:


如果mergedBatches不应包含对message2.Batches条目的引用,则可以使用解构:
单行acc.push({ ...cur })应该更容易理解,没有括号;
在最新情况下进行null检查:if/else可以返回undefined。






const message2 = {
  Batches: [
    {Batch: "AA", Lines: 1 },
    {Batch: "BB", Lines: 2 },
    {Batch: "BB", Lines: 6 }
  ]
}

const Worker = {
  Batches: [
    {Batch: "AA", Lines: 2 },
    {Batch: "BB", Lines: 3 },
  ]
}

const mergedBatches = message2.Batches.reduce((acc, cur) => {
  const prev = acc.find(x => x.Batch === cur.Batch)

  if (prev) prev.Lines += cur.Lines
  else acc.push(cur)

  return acc
}, [])

mergedBatches.forEach((mb) => {
  const wb = Worker.Batches.find(x => x.Batch === mb.Batch)

  if (wb && wb.Lines < mb.Lines ) mb.Lines = wb.Lines
})

console.log(mergedBatches)

07-28 10:06