JS递归过滤树形结构数组对象--模糊查询

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        const { log } = console
        let arr = [
            {
                title: '你吗?',
                children: [
                    {
                        title: '很好啊',
                        children: []
                    },
                    {
                        title: '吗',
                        children: [
                            {
                                title: '好呀',
                                children: []
                            }
                        ]
                    }
                ]
            },
            {
                title: '卡卡卡',
                children: [
                    {
                        title: '非常好芬',
                        children: []
                    }
                ]
            },
            {
                title: '好卡',
                children: [
                    {
                        title: '非常芬',
                        children: []
                    }
                ]
            },
            {
                title: '第三方的好',
                children: []
            },
            {
                title: '第三方的',
                children: [
                    {
                        title: '的',
                        children: [] 
                    }
                ]
            }
        ]

        let onRecursionData = (arr, val) => {
            let newarr = []
            arr.forEach(item => {
                if (item.children && item.children.length) {
                    let children = onRecursionData(item.children, val)
                    let obj = {
                        ...item,
                        children
                    }
                    if (children && children.length) {
                        newarr.push(obj)
                    } else if(item.title.includes(val)){
                        newarr.push({ ...item })
                    }
                } else {
                    if (item.title.includes(val)) {
                        newarr.push(item)
                    }
                }
            })
            return newarr
        }

        let result = onRecursionData(arr, '好')
        log(result)
    </script>
</body>

</html>

  参考文章:https://blog.csdn.net/qq_43432158/article/details/122846110

posted @ 2022-07-27 08:40  前端小沫  阅读(688)  评论(0编辑  收藏  举报