//扁平化json数据转树形结构
function treeData(list, id, pid, children) {
    var clone = JSON.parse(JSON.stringify(list));
    return clone.filter(function (father) {
        var childlist = clone.filter(function (child) {
            return father[id] == child[pid];
        });
        if (childlist.length > 0) {
            father[children] = childlist;
        }
        return father[pid] == 0;
    });
}

var dataa=[{id:1,parentId:0,name:"测试1"},{id:2,parentId:1,name:"测试2"}]

$(function(){
    var t = treeData(dataa,"id","parentId","children");
    console.log(t)
})

PS:错误的JSON

//错误1
[{id:1,name:"测试1"}]

//错误2
[{name:"测试1",parentId:0}]

版权声明:本文为原创文章,版权归 吾爱博客 所有,转载请联系博主获得授权!
本文地址:https://www.52bd.net/html/30.html

发表评论

正在加载 Emoji
×