使用 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];
}, []);

解释

  1. 使用 reduce 函数遍历 data 数组。
  2. reduce 函数的回调函数中,使用 map 函数遍历 diVoList 数组,并将每个元素转换为新的对象。
  3. map 函数中,使用 prev.length 来计算 serialkey,以确保它们在最终数组中是唯一的。
  4. 将新创建的对象添加到 prev 数组中,并返回更新后的 prev 数组。
  5. 最终,reduce 函数返回包含所有新对象的数组。

通过使用 reduce 函数,我们能够将原本使用嵌套循环的代码简化为一行代码,并且代码的可读性也得到了提升。

使用 reduce 优化 JavaScript 代码:将嵌套循环转换为简洁的数组操作

原文地址: http://www.cveoy.top/t/topic/n0oo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录