三维数组递归取对象

原数组:

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));

 

源地址: 三维数组取值

posted @ 2022-10-27 20:02  不如饲猪  阅读(23)  评论(0编辑  收藏  举报