获取对象数组中符合条件的key值

不知道怎么写了,求帮助。

[
    {
      "pid": "0",
      "name": "智慧定位",
      "level": "1",
      "industry_id": "37",
      "scene": [
        {
          "pid": "37",
          "name": "公车监管",
          "level": "2",
          "scene_id": "38"
        }
      ]
    },
    {
      "pid": "0",
      "name": "智慧工地",
      "icon": "",
      "level": "1",
      "industry_id": "39",
      "scene": [
        {
          "pid": "39",
          "name": "智能安全帽",
          "icon": "",
          "level": "2",
          "scene_id": "40"
        },
        {
          "pid": "39",
          "name": "智慧工地-综合",
          "icon": "",
          "level": "2",
          "scene_id": "41"
        }
      ]
    }
]

想知道scene_id为41的对象的industry_id

阅读 5.4k
2 个回答
function findID(arr){
  let id;
  arr.forEach(value =>{  
      for(key in value){
        if(key == 'scene'){
          for(let i = 0; i<value[key].length; i++){
            if(value[key][i].scene_id == '41'){
              id = value.industry_id;
              break;
            }
          }      
        }
       if(id) 
         break;
      }
  });
  return id;
}
console.log(findID(arr));

首先搞清思路,这是一个数组,数组里的结构就是一个对象,一个对象里面有一个industry_id 属性。那么直接遍历不就是了嘛。

var arr = [
    {
      "pid": "0",
      "name": "智慧定位",
      "level": "1",
      "industry_id": "37",
      "scene": [
        {
          "pid": "37",
          "name": "公车监管",
          "level": "2",
          "scene_id": "38"
        }
      ]
    },
    {
      "pid": "0",
      "name": "智慧工地",
      "icon": "",
      "level": "1",
      "industry_id": "39",
      "scene": [
        {
          "pid": "39",
          "name": "智能安全帽",
          "icon": "",
          "level": "2",
          "scene_id": "40"
        },
        {
          "pid": "39",
          "name": "智慧工地-综合",
          "icon": "",
          "level": "2",
          "scene_id": "41"
        }
      ]
    }
]
arr.forEach(item => console.log(item.industry_id))
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题