首页 > 其他分享 >三维数组递归取对象

三维数组递归取对象

时间:2022-10-27 20:13:00浏览次数:90  
标签:arr name 递归 三维 ret childList 数组 var id

原数组:

arr=[
  { name: '北京', id: 110000, childList: [{ name: '北京', id: 110001, childList: [  { name: '东城', id: 110101},{ name: '西城', id: 110102} ] }] },
  { name: '天津', id: 120000, childList: [{ name: '天津', id: 120001, childList: [  { name: '和平', id: 120101},{ name: '河东', id: 120102} ] }] },
   ....
  { name: '广东', id: 440000, childList: [{ name: '广州', id: 440001, childList: [  { name: '荔湾', id: 440101},{ name: '越秀', id: 440102} ] }] }
]

 

方法:

function find(list, id) {
    return list && id? (function filter(arr) {
        for (var i = 0; i < arr.length; ++i) {
            var itemId = arr[i].id;
            var children = arr[i].childList || [];
            var _ret = arr[i];
            if (id === itemId) {
                return _ret;
            } else if (children.length) {
                _ret = filter(children);
                if (_ret) return _ret;
            }
        }
        return null;
    })(list) : null;
}

console.dir(find(arr, 110101));

 

源地址: 三维数组取值

标签:arr,name,递归,三维,ret,childList,数组,var,id
From: https://www.cnblogs.com/ifeelthecall/p/16833562.html

相关文章