父母和孩子创建的json数据问题

时间:2019-05-31 05:16:42

标签: javascript json

for(var d in response.data) {
    var item = response.data[d];
    console.log("test-1234=="+JSON.stringify(item));
}

如果您获取数据,则数据如下所示。

test-1234=={"id":3,"isLeaf":"false","name":"bang","pid":0,"didabled":null}
test-1234=={"id":4,"isLeaf":"true","name":"test1","pid":3,"didabled":null}
test-1234=={"id":5,"isLeaf":"true","name":"test2","pid":3,"didabled":null}
test-1234=={"id":6,"isLeaf":"false","name":"test3","pid":0,"didabled":null}

我想基于pid建立父母与孩子之间的关系。
像下面。 请给我一个解决方案。

[
{
    name: 'bang',
    id: 3,
    pid: 0,
    dragDisabled: true,
    children: [
        {
            name: 'test1',
            id: 4,
            isLeaf: true,
            pid: 3
        },
       {
            name: 'test2',
            id: 5,
            isLeaf: true,
            pid: 3
        }
    ]
},
 {
            name: 'test3',
            id: 6,
            isLeaf: true,
            pid: 0
        }
]

2 个答案:

答案 0 :(得分:0)

尝试这样。

var arr = [
  { "id": 3, "isLeaf": "false", "name": "bang", "pid": 0, "didabled": null },
  { "id": 4, "isLeaf": "true",  "name": "test1", "pid": 3, "didabled": null },
  { "id": 5, "isLeaf": "true",  "name": "test2", "pid": 3, "didabled": null },
  { "id": 6, "isLeaf": "false", "name": "test3", "pid": 0, "didabled": null },
  { "id": 7, "isLeaf": "true", "name": "test\43", "pid": 4, "didabled": null }
]

var res = [];

for(var d in arr) {
    var item = arr[d];
    if(item.pid != 0){
      findParentAndPush(item)
    } else {
      item.children = [];
      res.push(item);
    }
}
  
function findParentAndPush(item){
  var filtered = arr.filter(data => data.id === item.pid);
  item.children = [];
  filtered[0].children.push(item)
}

console.log(res)

答案 1 :(得分:0)

在这种情况下,您可以使用递归来构建具有任意结构/深度的树:

var arr = [
  { "id": 3, "isLeaf": "false", "name": "bang", "pid": 0, "didabled": null },
  { "id": 4, "isLeaf": "true",  "name": "test1", "pid": 3, "didabled": null },
  { "id": 5, "isLeaf": "true",  "name": "test2", "pid": 3, "didabled": null },
  { "id": 6, "isLeaf": "false", "name": "test3", "pid": 0, "didabled": null },
  { "id": 7, "isLeaf": "true",  "name": "test4", "pid": 5,  "didabled": null }
]

function BuildTree(data) {
  var tree = [];
  for (var node of data) {
    if (data.filter(x => x.id == node.pid).length == 0) {
      tree.push(node);
      ProcessNode(node, data);
    }
  }
  return tree;
}

function ProcessNode(node, data) {
  node.children = data.filter(x => x.pid == node.id)
  for (var child of node.children)
    ProcessNode(child, data);
}

console.log(BuildTree(arr));