js 平级数据转换为树桩结构递归

本文介绍如何使用 Vue.js 通过递归方法构建动态数据结构,并展示在组件中。通过 `makedata` 和 `makethree` 函数,实现从原始数据到层次结构的转换,适合理解组件间父子关系的管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <div>
      {{newArray}}
    </div>
  </div>
</template>

<script>


export default {
  name: 'App',
  components: {
   
  },
  data () { 
    return { 
      array : [
       {  id : 1 },
       {  parentId : 1 ,id :2   },
       {  id : 3 },
       {  parentId : 3 ,  id : 4 },
       {  parentId : 4 ,id : 5 },
       {  parentId : 5 ,id : 6 },
       {  parentId : 6 ,id : 7 },
      ],
      newArray : [
        // {  id : 1 , children :[]},
        // {  id : 3 , children :[]} 
      ],
    }
  },
  created () {
    this.makedata()
  },
  methods : { 
     makedata (){ 
       this.array.forEach( item1=> { 
        // console.log(Object.keys(item1).length);
          if (Object.keys(item1).length=='1') {
            this.newArray.push({ id : item1.id , children :[]})
          }
       })
       this.makethree( this.newArray)
     },
    makethree( data ){ 
     data.forEach( item => { 
        this.array.forEach ( item1 => { 
             if (item.id == item1.parentId) {
             item.children.push({...item1 , children : []})
              this.makethree( item.children)
          }
        })
       })
     },

  }
}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值