vue 对一个多级对象数组获取各级名称组合成的字符串

const dataList = [
    {
        id: 1,
        name: “广东省”,
        items: [
            {
                id: 11,
                name: “深圳市”,
                items: [
                    {
                          id: 112,
                          name: “福田区”,
                          items: []
                     },
                ]
            },
        ]
    },
]

以上数据在已知 id = 112 的情况下,如何获取到文本:“广东省 > 深圳市 > 福田区” ?

递归 一下 vue里 nodePathArray 需要在 data里定义 。然后在methods里加上 getNodeRoute 调用就是 this.getNodeRoute(xx,xx) 还是有就是 getNodeRoute 里的nodePathArray.push 改成 this.nodePathArray.push


<!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>
    const dataList = [
        {
            id: 1,
            name: "广东省",
            items: [
                {
                    id: 11,
                    name: "深圳市",
                    items: [
                        {
                            id: 112,
                            name: "福田区",
                            items: [
                                {
                                    id: 1121,
                                    name: "福田区666",
                                    items: [

                                    ]
                                },
                            ]
                        },
                    ]
                },
            ]
        },
    ];

    // function lu(data,id){
    //     data.map((item)=>{

    //     })
    // }




    // 首先我们先定义个数组,用来保存路径节点id
    let nodePathArray = []

    // (tree为目标树,targetId为目标节点id)
    function getNodeRoute(tree, targetId) {
        for (let index = 0; index < tree.length; index++) {
            if (tree[index].items) {
                let endRecursiveLoop = getNodeRoute(tree[index].items, targetId)
                if (endRecursiveLoop) {
                    nodePathArray.push(tree[index].name)
                    return true
                }
            }
            if (tree[index].id === targetId) {
                nodePathArray.push(tree[index].name)
                return true
            }
        }
    }

    getNodeRoute(dataList, 1121) //查找id为112的节点路径
    console.log(nodePathArray.reverse().join('-'));

</script>

</html>

写一个递归函数。

    let res = [];
    let lastres;
function getPrivece(data,id){
            if(data && data.id != id){
                getPrivece(data.items[0],id)
                res.push(data.name)
            }
            return res
    }
getPrivece(dataList[0],122).reverse().forEach(item=>{
    return  lastres = lastres?lastres+">" +item:item
})
console.log(lastres);