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

求助:Angular中如何获取动态嵌套对象里的code:ENABLE_COMPANY_CODE键值?

在Angular中从动态嵌套对象中查找指定code的键值对

问题说明

需要在Angular项目里,从动态可变结构的嵌套对象中定位code: "ENABLE_COMPANY_CODE"的键值对,尝试了以下代码但未成功,对象结构参考截图:

尝试过的代码

if(user.authorizations)
{
   
    user.authorizations.forEach(obj=>
        {
            for (const [key, value] of Object.entries(obj))
            {
                console.log(key);
                console.log(value);
                if(value=="ENABLE_COMPANY_CODE")
                {
                    console.log("value is"+value);
                }
            }

        })
    
}

对象结构截图

嵌套对象结构截图

解决方案

从截图可见,user.authorizations中的每个元素是包含code属性的对象,而非直接的键值对映射。之前的代码错误地遍历了对象的键值对,正确的做法是直接访问code属性,同时用递归适配动态嵌套结构:

// 递归遍历函数,查找目标code对应的对象
findTargetAuthorization(authList: any[], targetCode: string): any | null {
  for (const auth of authList) {
    // 检查当前对象是否匹配目标code
    if (auth.code === targetCode) {
      return auth;
    }
    // 如果存在子级数组(比如children字段,根据实际结构调整),递归查找
    if (auth.children && Array.isArray(auth.children)) {
      const result = this.findTargetAuthorization(auth.children, targetCode);
      if (result) return result;
    }
  }
  return null;
}

// 调用示例
if (user.authorizations) {
  const targetItem = this.findTargetAuthorization(user.authorizations, "ENABLE_COMPANY_CODE");
  targetItem ? console.log("找到目标对象:", targetItem) : console.log("未匹配到指定code");
}

关键说明

  1. 递归逻辑可适配任意层级的嵌套结构,完美应对动态可变的对象类型;
  2. 直接访问code属性比遍历所有键值对更高效;
  3. 若你的嵌套子级不是children字段,替换为实际的子数组字段名即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 21:10:22