使用 reduce 优化 JavaScript 代码:将嵌套循环转换为简洁的数组操作
使用 reduce 优化 JavaScript 代码:将嵌套循环转换为简洁的数组操作
本文将展示如何使用 reduce 函数来优化 JavaScript 代码,将嵌套循环转换为简洁的数组操作。我们将使用一个具体的示例来说明如何将 forEach 循环转换为 reduce 函数。
原始代码(使用 forEach)
let arr: any = [];
data.forEach((item: any, index2: number) => {
const len = item?.diVoList?.length;
item.diVoList?.forEach((ite: any, index: number) => {
arr = [
...arr,
{
serial: index2 + 1,
projectType: item.projectType,
projectId: item.projectId,
projectName: item.projectName,
targetDi: item.targetDi,
actualDi: item.actualDi,
spm: ite.spm,
department: ite.department,
targetDis: ite.targetDi,
actualDis: ite.actualDi,
span: index === 0 ? len : 0,
},
];
return arr;
});
return arr;
});
const tableData = arr.map((item1: any, index: number) => {
item1.key = index;
return item1;
});
优化后的代码(使用 reduce)
const tableData = data.reduce((prev: any, curr: any) => {
const len = curr?.diVoList?.length || 0;
const newData = curr.diVoList?.map((item: any, index: number) => ({
serial: prev.length + index + 1,
projectType: curr.projectType,
projectId: curr.projectId,
projectName: curr.projectName,
targetDi: curr.targetDi,
actualDi: curr.actualDi,
spm: item.spm,
department: item.department,
targetDis: item.targetDi,
actualDis: item.actualDi,
span: index === 0 ? len : 0,
key: prev.length + index
}));
return [...prev, ...newData];
}, []);
解释
- 使用
reduce函数遍历data数组。 - 在
reduce函数的回调函数中,使用map函数遍历diVoList数组,并将每个元素转换为新的对象。 - 在
map函数中,使用prev.length来计算serial和key,以确保它们在最终数组中是唯一的。 - 将新创建的对象添加到
prev数组中,并返回更新后的prev数组。 - 最终,
reduce函数返回包含所有新对象的数组。
通过使用 reduce 函数,我们能够将原本使用嵌套循环的代码简化为一行代码,并且代码的可读性也得到了提升。
原文地址: http://www.cveoy.top/t/topic/n0oo 著作权归作者所有。请勿转载和采集!