美文网首页
js 将数组对象按分类转为树形结构

js 将数组对象按分类转为树形结构

作者: 冰雪_666 | 来源:发表于2020-05-13 15:10 被阅读0次

    有如下数据结构,例如:

    var industry_list =[
        {
            "parent_ind" : "女装",
            "name" : "连衣裙"
        },
        {
            "name": "女装"
        },
        {
            "parent_ind" : "女装",
            "name" : "半身裙"
        },
        {
            "parent_ind" : "女装",
            "name" : "A字裙"
        },
        {
            "name": "数码"
        },
        {
            "parent_ind" : "数码",
            "name": "电脑配件"
        },
        {
            "parent_ind" : "电脑配件",
            "name": "内存"
        },
        {
            "parent_ind" : "数码",
            "name": "CPU"
        },
        {
            "parent_ind" : "电脑配件",
            "name": "GPU"
        },
        
        ]
    

    为了取用方便,我们希望可以将其转换为树状格式,例如:

    {
        "女装": {
            "连衣裙": {},
            "半身裙": {},
            "A字裙": {}
        },
        "数码": {
            "电脑配件": {
                "内存": {},
                "GPU": {}
            },
            "CPU": {}
        }
    }
    

    实现一个方法完成这个转换,如下:主要用到修改引用类型地址


    微信图片_20200513150623.png
    function convert_forma( data ) {
        let cache = {};
        let _data = {};
        let parent_arr = [], child_arr = [];
        for( let arr of data ) {
            (arr.parent_ind ? child_arr : parent_arr).push(arr);
        }
        while( parent_arr.length || child_arr.length ) {
            
            if( parent_arr.length ) {
                let first = parent_arr.shift();
                _data[first.name] = {};
                cache[ first.name ] = _data[first.name];
    
            } else {
                let first = child_arr.shift();
                if( first.parent_ind in cache ) {
                    cache[ first.parent_ind ][ first.name ] = {};
                     //通过引用类型赋值,修改指向地址
                    cache[ first.name ] = cache[ first.parent_ind ][ first.name ];
                }else{
                    child_arr.push(first)
                }
    
            }
        }
        cache=null;
        return _data;
    }
    console.log(convert_forma( industry_list))
    
    

    相关文章

      网友评论

          本文标题:js 将数组对象按分类转为树形结构

          本文链接:https://www.haomeiwen.com/subject/hdvnnhtx.html