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

如何覆盖嵌套于type1中的所有val属性值?

覆盖嵌套在type1中的val值的方法

给你几种实用的实现方式:

1. 直接遍历外层对象(适合固定层级结构)

如果你的对象结构和示例一致,type1都直接在object1/object2这类外层对象下,用for...in循环最直接:

const newValue = 2; // 你要设置的新值

for (const objKey in myList) {
  const currentObj = myList[objKey];
  // 检查当前对象是否包含type1属性
  if (currentObj.type1) {
    currentObj.type1.val = newValue;
  }
}

2. 用Object.values()简化遍历逻辑

这种写法更简洁,把外层对象的值提取成数组后遍历:

const newValue = 2;

Object.values(myList).forEach(item => {
  if (item.type1) {
    item.type1.val = newValue;
  }
});

3. 递归遍历(适配更深层级的嵌套)

如果不确定type1会出现在哪一层级,用递归函数可以遍历所有嵌套对象,找到所有type1并修改:

function updateAllType1Val(targetObj, newValue) {
  for (const key in targetObj) {
    const value = targetObj[key];
    if (typeof value === 'object' && value !== null) {
      // 找到type1就更新val
      if (key === 'type1') {
        value.val = newValue;
      }
      // 递归处理下一层对象
      updateAllType1Val(value, newValue);
    }
  }
}

// 调用函数,传入目标对象和新值
updateAllType1Val(myList, 2);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 19:32:05