vue 使用filter 把无限极分类遍历为树形结构

<script setup lang="ts">
interface listType {
    id: number
    url: string
}
const data = [
    {
        id: 1,
        url: '/_nuxt/assets/images/america.png'
    },
    {
        id: 2,
        url: '/_nuxt/assets/images/embass.png'
    },
    {
        id: 3,
        url: '/_nuxt/assets/images/qzsq_sqdt.png'
    }
]
const list = ref<listType[]>([])

// const list = ref({} as listType[])
list.value = data
// list.value = list.value.filter(item => item.id !== id)

const arr = [
    { id: 1, pid: 0, name: '四川' },
    { id: 2, pid: 0, name: '山东' },
    { id: 3, pid: 0, name: '河南' },
    { id: 4, pid: 3, name: '长治' },
    { id: 5, pid: 3, name: '孝感' },
    { id: 6, pid: 1, name: '广元' },
    { id: 7, pid: 1, name: '雅安' },
    { id: 8, pid: 2, name: '德州' }
]
let newarr = []
arr.forEach(r => {
    r.child = arr.filter(item => item.pid == r.id)
    if (r.pid == 0) {
        newarr.push(r)
    }
})
console.log(newarr)
</script>

<template></template>

<style scoped lang="scss">
img {
    opacity: 1;
}
</style>
posted @ 2023-10-27 22:41  猖狂的小山猪  阅读(91)  评论(0编辑  收藏  举报