You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将对象中所有isGood属性统一设置为true?

解决将对象中所有isGood属性设为true的问题

看起来你踩了lodash _.forOwn的一个常见小坑!报错value.forEach is not a function的核心原因是你把回调函数的参数顺序搞反了。

问题根源

_.forOwn的回调函数参数顺序是(value, key),而你写成了(key, value)——这导致你实际拿到的value是对象的键名(字符串类型),字符串当然没有forEach方法,所以报错了。

修正后的代码

首先把参数顺序调整正确,然后就能正常遍历每个数组元素,修改isGood的值了:

_.forOwn(this.editAlertsByType, (value, key) => {
  // 加个数组判断,避免万一有非数组属性导致报错
  if (Array.isArray(value)) {
    value.forEach(element => {
      element.isGood = true;
    });
  }
});

如果能确定this.editAlertsByType的所有属性值都是数组,也可以简化掉判断:

_.forOwn(this.editAlertsByType, (value) => {
  value.forEach(element => {
    element.isGood = true;
  });
});

不用lodash的原生实现方案

如果你不想依赖lodash,用原生JS也能轻松实现:

// 获取对象所有属性值(也就是那些数组),然后逐层遍历
Object.values(this.editAlertsByType).forEach(arr => {
  arr.forEach(element => {
    element.isGood = true;
  });
});

这样就能把所有isGood属性都设置为true了,试试吧!

内容的提问来源于stack exchange,提问作者Leo Messi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:36:50