如何将平面多分支数据转换为分层JSON?

时间:2016-06-14 08:03:31

标签: javascript node.js algorithm tree

startService()

以上是我从数据库中获取的数据。每个人都有[ { "id": "a", "pid": "a", "name": "AA", }, { "id": "b", "pid": "a", "name": "BB", }, { "id": "c", "pid": "a", "name": "CC", }, { "id": "x", "pid": "b", "name": "XX", } ] idpid指向该人的更高级别人pid。如果某人的级别最高,则id等于id

我想将原始数据转换为分层JSON,如下所示:

pid

我正在使用Node.js.

2 个答案:

答案 0 :(得分:4)

我建议您创建一个树并将id === pid作为树的根,这适用于未分类的数据。

  

工作原理:

     

基本上,对于数组中的每个对象,id为新对象构建一个新对象parentid

     

例如:

{ "id": 6, "pid": 4 }
     

首先使用id生成此属性:

"6": {
    "id": 6,
    "pid": 4
}
     

然后使用pid

"4": {
    "children": [
        {
            "id": 6,
            "pid": 4
        }
    ]
},
     

虽然对所有对象进行了类似处理,但我们最终得到了一棵树。

     

如果id === pid,则找到根节点。这是后来回归的对象。



var data = [
        { "id": "f", "pid": "b", "name": "F" },
        { "id": "e", "pid": "c", "name": "E" },
        { "id": "d", "pid": "c", "name": "D" },
        { "id": "c", "pid": "b", "name": "C" },
        { "id": "a", "pid": "a", "name": "A" },
        { "id": "b", "pid": "a", "name": "B" }
    ],
    tree = function (data) {
        var r, o = Object.create(null);
        data.forEach(function (a) {
            a.children = o[a.id] && o[a.id].children;
            o[a.id] = a;
            if (a.id === a.pid) {
                r = a;
            } else {
                o[a.pid] = o[a.pid] || {};
                o[a.pid].children = o[a.pid].children || [];
                o[a.pid].children.push(a);
            }
        });
        return r;
    }(data);

console.log(tree);




答案 1 :(得分:1)

受尼娜的回答影响,这是我的决议,仅供记录。



function corrugate(data){
  var root = "";
  return data.reduce((t,o) => {
    	                       o.id === o.pid && (root = o.id);
  	                           t[o.id]  ? t[o.id].name = o.name
  	                                    : t[o.id] = {id: o.id, name: o.name};
  	                           t[o.pid] ? o.pid !== o.id ? t[o.pid].children.push(t[o.id])
  	                                                     : t[o.pid].children = t[o.pid].children || []
  	                                    : t[o.pid] = {id: o.pid, children: [t[o.id]]};
  	                           return t;
                              },{})[root];
}

var   data = [{ "id": "f", "pid": "b", "name": "F" },
              { "id": "e", "pid": "c", "name": "E" },
              { "id": "b", "pid": "a", "name": "B" },
              { "id": "d", "pid": "c", "name": "D" },
              { "id": "c", "pid": "b", "name": "C" },
              { "id": "a", "pid": "a", "name": "A" }
             ];
console.log(corrugate(data));