JavaScript字符串排序(按名称排序)


<!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>

</body>
<script>
    let arr = [
        {
            name: "移动",
            id: 1,
            children: [
                {
                    name: "联通-004",
                    id: 4,
                    children: [{
                        name: "电信-007",
                        id: 7
                    },
                    {
                        name: "无线网-008",
                        id: 8
                    },
                    {
                        name: "电信-008",
                        id: 9
                    }]
                },
                {
                    name: "123-005",
                    id: 5
                },
                {
                    name: "联通-006",
                    id: 6
                }]
        },
        {
            name: "001通讯",
            id: 2
        },
        {
            name: "003通讯",
            id: 3
        },
        {
            name: "002通讯",
            id: 10
        }
    ]

    function recursion(data) {
        data.map(e => {
            if (e.children) {
                e.children.sort(function (a, b) { return a.name.localeCompare(b.name, 'zh-CN') })
                recursion(e.children)
            }
        })
        return data
    }
    arr.sort(function (a, b) { return a.name.localeCompare(b.name, 'zh-CN') })
    arr = recursion(arr)
    console.log(arr);
</script>

</html>

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/280074.html

(0)
上一篇 2022年8月12日
下一篇 2022年8月12日

相关推荐

发表回复

登录后才能评论