陈伟华

三层取值的问题

const address = [

  {

    id: 1,

    name: '北京市',

    children: [

      {

        id: 11,

        name: '海淀区',

        children: [

          {

            id: 111,

            name: '中关村',

          }

        ]

      },

      {

        id: 12,

        name: '朝阳区',

      },

    ],

  },

  {

    id: 2,

    name: '河北省'

  }

function getCidList(val, id) {

        let cid_list = []

        val.forEach((item, index) => {

            if (item.id == id) {

                cid_list = [item.name]

                return false

            } else {

                if (item.children) {

                    let newCid_list = [item.id]

                    let list = nodefun(item.children, id, newCid_list)

                    if (list) {

                        cid_list = list

                    }

                }

            }

        })

  // 递归函数

        function nodefun(newVal, newId, newCid_list) {

            let flag = false

            newVal.forEach(j => {

                if (j.id == newId) {

                    newCid_list.push(j.name)

                    flag = true

                } else {

                    if (j.children) {

                        let cid_list = JSON.parse(JSON.stringify(newCid_list))

                        cid_list.push(j.name)

                        let list = nodefun(j.children, newId, cid_list)

                        if (list) {

                            newCid_list = list

                            flag = true

                        }

                    }

                }

            })

            if (flag) {

                return newCid_list

            }

        }

        return cid_list

    }

 

function getNameById(address,num){

  var a = getCidList(address,num)

return a[a.length-1];

}

getNameById(address,num);

posted on 2021-10-26 10:45  陈伟华  阅读(90)  评论(0编辑  收藏  举报

导航