zoukankan      html  css  js  c++  java
  • 数组转树

    将input数据格式转换为output数据格式

    let input =  [{
        id: 1, val: '学校',  parentId: null
    },{
        id: 2, val: '班级1', parentId: 1
    },{
        id: 3, val: '班级2', parentId: 1
    },{
        id: 4, val: '学生1', parentId: 2
    },{
        id: 5, val: '学生2', parentId: 3
    },{
        id: 6, val: '学生3', parentId: 3
    }]
    
    let output = {
        id: 1,
        val: '学校',
        children: [{
            id: 2,
            val: '班级1',
            children: [
                {
                    id: 4,
                    val: '学生1',
                    children: []
                }
            ]
        }, {
            id: 3,
            val: '班级2',
            children: [
                {
                    id: 5,
                    val: '学生2',
                    children: []
                },{
                    id: 6,
                    val: '学生3',
                    children: []
                }
            ]
        }]
    }

    实现方式

    function arrToTree(input){
        let { id,val } = input.find(item => item.parentId === null)
        let output = {
            id,val
        }
        let toTree = (id,input) => {
            let children = []
            for(let i = 0;i < input.length;i++){
                let item = input[i]
                if(id == item.parentId){
                    children.push({
                        id:item.id,
                        val:item.val,
                        children:toTree(item.id,input)
                    })
                }
            } 
            return children
        }
        output.children = toTree(id,input)
        return output
    }
    以自己现在的努力程度,还没有资格和别人拼天赋
  • 相关阅读:
    vue语法
    第3章 语言基础(上)
    第2章 HTML中的JavaScript
    第1章 什么是JavaScript
    附录 A ES6附加特性
    第14章 跨浏览器开发技巧
    第13章 历久弥新的事件
    第12章 DOM操作
    第11章 代码模块化
    第10章 正则表达式
  • 原文地址:https://www.cnblogs.com/zhenjianyu/p/13367164.html
Copyright © 2011-2022 走看看