猿问

js多层嵌套,只知道最后一个值,如何遍历获取到所有父级

数据结构有多个层级嵌套,如下: 目前获取到的值只有 "521" 这个值,如何遍历获取到 "1045-SCG"和"968"

数据结构:[
  {    "value": "1045-SCG",    "label": "蛟龙系统",    "children": [
      {        "value": "968",        "label": "蛟龙号",        "children": [{          "value": "521",          "label": "翅膀",
        }]
      }
    ]
  },
  {    "value": "1044-SCG",    "label": "111",    "children": []
  },
  ,
  {    "value": "1036-SCG",    "label": "海原系统",    "children": [
      {        "value": "264",        "label": "我要下单",        "children": [
          {            "value": "271",            "label": "下单模板",            "children": []
          }
        ]
      }]
  }
]


达令说
浏览 1853回答 2
2回答

UYOU

function&nbsp;l(data,&nbsp;val)&nbsp;{&nbsp;&nbsp;for(var&nbsp;i=0;i<data.length;i++){&nbsp;&nbsp;&nbsp;&nbsp;if(data[i]&&data[i].value&nbsp;==&nbsp;val){&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;[]; &nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;&nbsp;&nbsp;if(data[i]&&data[i].children){&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;d&nbsp;=&nbsp;l(data[i].children,val);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if(d)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;d.concat(data[i].value); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;} } l(data,'271');

Qyouu

简单对象没有自己是哪个对象属性的记录,你得重新设计数据结构
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答