欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js递归返回想要的值

程序员文章站 2022-06-10 20:17:43
...

递归返回想要的值

    /**
     * 递归数组返回想要的值,返回所有匹配到的节点组成的数组
     * @param {Array}           list        要递归的数组
     * @param {String}          childKey    子集字段
     * @param {String}          key         要匹配的字段(===判断)
     * @param {String/Number}   val         要匹配字段所对应的值(===判断)
     */
    function getNode(list, childKey, key, val, result = []) {
        list.forEach(item => {
            if (item[key] === val) {
                result.push(item);
            }
            if (item[childKey] && item[childKey].length > 0) {
                getNode(item[childKey], childKey, key, val, result)
            }
        });
        return result
    };

 

例子:

    let tree = [{
        name: '水果',
        type: 'group',
        id: 1,
        children: [{
            name: '热带水果',
            type: 'group',
            id: 11,
            children: [{
                name: '香蕉',
                type: 'goods',
                id: 111,
            },{
                name: '菠萝',
                type: 'goods',
                id: 112,
            },{
                name: '榴莲',
                type: 'goods',
                id: 113,
            }]
        },{
            name: '温带水果',
            type: 'group',
            id: 12,
            children: [{
                name: '苹果',
                type: 'goods',
                id: 121,
            },{
                name: '西瓜',
                type: 'goods',
                id: 122,
            }]
        }]
    },{
        name: '粮食',
        type: 'group',
        id: 2,
        children: [{
            name: '温带作物',
            type: 'group',
            id: 21,
            children: [{
                name: '小麦',
                type: 'goods',
                id: 211,
                children: [{
                    name: '黑小麦',
                    type: 'goods',
                    id: 2111
                },{
                    name: '白小麦',
                    type: 'goods',
                    id: 2112
                }]
            }]
        }]
    }];

    let a = getNode(tree, 'children', 'type', 'goods')
    let c = getNode(tree, 'children', 'id', 2111 )

输出结果:

js递归返回想要的值

相关标签: 前端笔记