JavaScript 在多维数组或数组对象嵌套的数据结构中查找一个值

3,730 阅读1分钟

函数

/**
 * 在数组中查找指定的项 ,支持多维数组 ,数组对象嵌套
 *
 * @param needle 要查找的值
 * @param haystack 被查找的数组
 * @param property 当被查找项是对象时( 数组对象嵌套 )这个参数作为要查找的值的属性名称 ,如果是多维数组不会有任何影响
 * @param children 当被查找项是对象时( 数组对象嵌套 )这个参数作为子集合属性名称 ,如果是多维数组不会有任何影响
 * @return undefined | Object | *
 */
function array_search(needle, haystack, property = 'id', children = 'children', result = { search: undefined }) {
    
    result.search = haystack.find((value, index, arr) => {
        return property === '' ? value == needle : value[property] == needle
    })

    let child;

    if (result.search === undefined) {
        haystack.forEach((value, index, arr) => {
            child = Array.isArray(value) ? value : value[children]
            if (child.length >= 0 && result.search === undefined) {
                array_search(needle, child, property, result)
            }
        })
    }

    return result.search
}

数据结构

$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: [] },
        ]
    }
];

想问下有没有更简单的方法 ,或更优化的写法