递归查询省市区数据

  • 开发中需要用到省市区数据,但是后端只返回最里层城市的code值
  • code是省市区的唯一代码,name则是省市区的名称,children则是省市区下的子项
    /**
     * 根据code查询城市
     * 并查出所有父级
     * 原理 ===> 
     * 通过递归查找code与传入code相同
     * 且在查找相同code的同时,将上级内容传递进下级循环中
     * 如果code相同了,上级内容自然就能拿到
     * 因为不知道有多少个上级
     * 所以在查找到之后继续进行递归源数据(这里注意,并不是当前循环数据,而是最根本的数据)
     * 这个时候不需要传递当前级的内容,否则无限循环卡死
     */
    function getArea(json, code) {
        let names = [];
        let codes = [];
        function findCity(list, code, father) {
            const index = list.findIndex(ev => ev.code == code);
            if (index > -1) {
                const child = list[index];
                names.unshift(child.name);
                codes.unshift(child.code);
                father && names.unshift(father.name) && codes.unshift(father.code);
                father && findCity(json || [], father.code);
                return;
            }
            list.map(item => {
                if (item.children) {
                    findCity(item.children || [], code, item);
                }
            })
        }
        findCity(json, code);
        names = [...new Set(names)];
        codes = [...new Set(codes)];
        return { codes, names };
    }
    const list = getArea(cityJson, parseInt(code));
    console.log(list);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值