js reduce 的别样用法

let mergedItems = list.reduce((accumulator, currentItem) => {
  let existingItem = accumulator.find(
    (item) => item.manObject_name === currentItem.manObject_name
  );
  if (existingItem) {
    existingItem.laborCostHand += currentItem.laborCostHand; //劳务费
    existingItem.workDay += currentItem.workDay; //工日
    existingItem.laborCost += currentItem.laborCost; //劳务费 不函数
  } else {
    accumulator.push({ ...currentItem });
  }
  return accumulator;
}, []);

reduce 用法 参考 JS 中 reduce()方法及使用详解_js reduce-CSDN博客

reduce 方法常用来取数字和,但是也可以initialValue 也可以传递数组或者对象,用来最终生成 新的数组或者对象,这点非常实用。

上面例子中的初始值是个空数组,之后不断地往里面塞入新的元素或者对元素的属性进行相加等,操作,最终相当于过滤并且对数组元素相加的效果,非常实用,代码精简化。

注意这里 initialValue 是个空数组,而每次循环后 返回值还是个数组,循环结束之后就相当于对原数组list 做个过滤和相关操作(相加),呢么最后一次循环返回的数组结果就是我们需要的对象数组。尽量少的代码实现了我们想要的效果。 之后再用 mergeItem 接受一下最新值,即可实现了我们的逻辑。

相关推荐

  1. nc

    2024-07-19 08:04:01       60 阅读
  2. QueryWrapper

    2024-07-19 08:04:01       28 阅读
  3. axios

    2024-07-19 08:04:01       29 阅读
  4. React <> </>

    2024-07-19 08:04:01       29 阅读
  5. pymysql基本

    2024-07-19 08:04:01       55 阅读
  6. css_auto

    2024-07-19 08:04:01       50 阅读
  7. 关于QUOTENAME

    2024-07-19 08:04:01       56 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-19 08:04:01       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-19 08:04:01       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-19 08:04:01       58 阅读
  4. Python语言-面向对象

    2024-07-19 08:04:01       69 阅读

热门阅读

  1. AccessibilityEvent常用事件

    2024-07-19 08:04:01       20 阅读
  2. vue3封装el-table及实现表头自定义筛选

    2024-07-19 08:04:01       20 阅读
  3. jEasyUI 显示海量数据

    2024-07-19 08:04:01       20 阅读
  4. 团队高效地使用 Git 进行协同开发

    2024-07-19 08:04:01       20 阅读
  5. ArrayList

    2024-07-19 08:04:01       21 阅读