//扁平化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}]

本文由 吾爱 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

3 条评论

  1. 344085057
    344085057

  2. 344085057
    344085057

    123

    123

  3. 344085057
    344085057

添加新评论