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
        }
]

试试这样。

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": "test43", "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)

最新更新