在一维数组或多维数组中找到某个元素的索引

128 阅读1分钟

property:为需要查找的字段key

children:为子数组的key

const arr = [
    {
        id: 1,
        name: '一级菜单1',
        children: [
            { id: 2, name: '二级菜单1', children: [] },
            { id: 3, name: '二级菜单2', children: [] },
            { id: 4, name: '二级菜单3', children: [] },
        ]
    },
    {
        id: 5,
        name: '二级菜单1',
        children: [
            { id: 6, name: '二级菜单4', children: [] },
            { id: 7, name: '二级菜单5', children: [] },
            { id: 8, name: '二级菜单6', children: [] },
        ]
    }
];
function array_search(haystack,needle,path = [],property = "name",children = "children") {
                if (
                    haystack.some((item,index) => {
                    if (item[property] === needle) {
                        // path.push(item[property]);
                        path.push(index);
                        return true;
                    } else if (item[children]) {
                        // path.push(item[property]);
                        path.push(index);
                        if (array_search(item[children], needle, path)) {
                        return true;
                        } else {
                        path = [];
                        return false;
                        }
                    } else {
                        return false;
                    }
                    })
                ) {
                    return path;
                } else {
                    return null;
                }
            }
let result = array_search(arr,'二级菜单1');
console.log(result) // 输出[0,0]