javascript - 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));
解决方案
您可以使用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 });
这是否比您发布的代码“更好”是主观的。它有点短;这是否使它更具可读性或可维护性或更少?不同的人会给出不同的答案。
至于性能,几乎任何简单的迭代方法对于任何实际应用都将与另一种方法一样快。如果你有数百万个这样的批次,那么绝对不会让迭代变得“快”。
推荐阅读
- python - Python mysql自动提交对phpmyadmin不可见的数据
- ios - 我使用wheaterapi.com 并使用init URL(字符串:urlString)创建url。链接可与浏览器一起使用,但不能与应用程序一起使用。怎么修?
- java - 使用ffmpeg作为Java中的进程录制实时流
- docker - docker容器内的dompdf:file_put_contents(x / x)无法打开流:没有这样的文件或目录
- javascript - 如何使用 Laravel 调试栏检查文件上传?
- c# - 复杂的数学表达式 c#
- delphi - QuickReport:将详细信息带和子带保持在一页上
- python - 如何使用 bs4 获取 youtube 音乐历史?
- swift - 水平 UIcollectionView 滚动从右到左开始
- react-native - 跨应用程序重用 React Native 屏幕