三维数组取值

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} ] }] }
]

我现在的需求是搜索框
输入广东省、需要对应返回 广东省-以及广东省下面所有的市、区可以不用
输入广州市、需要对应返回 广东省-广州市-以及广州市下面所有的区
输入荔湾区、需要对应返回 广东省-广州市-荔湾区

请各位大哥大姐帮小弟看看...

阅读 1.6k
2 个回答
function find(list, place) {
    return list && place ? (function filter(arr, ret) {
        for (var i = 0; i < arr.length; ++i) {
            var name = arr[i].name;
            var children = arr[i].childList || [];
            var _ret = ret.concat([arr[i]]);
            if (!place.indexOf(name)) {
                return _ret.concat(children);
            } else if (children.length) {
                _ret = filter(children, _ret);
                if (_ret.length) return _ret;
            }
        }
        return [];
    })(list, []) : [];
}
console.dir(find(arr, "广东省"));
console.dir(find(arr, "广州市"));
console.dir(find(arr, "荔湾区"));

function search(target, searchText) {
    return target?.filter((item) => (match(item) || Boolean(search(item.childList, searchText).length))) || [];

    function match(item) {
        return item?.name?.includes(searchText);
    }
}
// 不过滤同级选项,找到即可
console.log(search(arr, '荔湾'));

function search2(target, searchText) {
    const result = [];

    const stack = [];
    function innerSearch(items) {
        for(const {id, name, childList} of items) {
            stack.push({
                id,
                name
            });
            if (name?.includes(searchText)) {
                result.push(stack.slice());
                continue;
            }
            if (childList?.length) {
                innerSearch(childList);
            }
            stack.pop();
        }
    }

    innerSearch(target);

    return result.map((item) => {
        let last = item.pop();
        let previous;
        while(item.length) {
            previous = item.pop();
            previous.childList = [last];
            last = previous;
        }
        return previous || last;
    });
}
// 过滤同级非匹配项
console.log(search2(arr, '荔湾'));
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏