for(var d in response.data) {
var item = response.data[d];
console.info("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": "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.info(res)