首页 > 解决方案 > Is For...In loop only option to create an object?

问题描述

Is For-In loop only option to create an object with properties or is there a better approach? I would like to create an object instead of array.

Currently it loop data.Batch using for-in loop and do some total calculation and property mapping.

For example:

let data = {
  Batch: {
    111: { BatchId: 111, Name: "Batch 1", Count2017: 100, Count2018: 100 },
    222: { BatchId: 222, Name: "Batch 2", Count2017: 200, Count2018: 300 }
  }
};

function calculateBatch(batch) {
  mappedObject = {};
  let grandTotal = 0;

  for (const batchId in data.Batch) {
    let total = data.Batch[batchId].Count2017 + data.Batch[batchId].Count2018;

    mappedObject[batchId] = {
      BatchId: batchId,
      Name: data.Batch[batchId].Name,
      Total: total
    };

    grandTotal += total
  }

  return {
      Batch: mappedObject,
      GrandTotal: grandTotal
  }
}

console.log(calculateBatch(data.Batch));

标签: javascriptnode.js

解决方案


您可以使用Object.keys()获取属性名称数组,然后.reduce()创建结果对象:

return Object.keys(batch).reduce(function(result, key) {
  let total = batch[key].Count2017 + batch[key].Count2018;
  result.Batch[key] = {
    BatchID: key,
    Name: batch[key].Name,
    Total: total
  };
  result.GrandTotal += total;
  return result;
}, { Batch: {}, GrandTotal: 0 });

这是否比您发布的代码“更好”是主观的。它有点短;这是否使它更具可读性或可维护性或更少?不同的人会给出不同的答案。

至于性能,几乎任何简单的迭代方法对于任何实际应用都将与另一种方法一样快。如果你有数百万个这样的批次,那么绝对不会让迭代变得“快”。


推荐阅读