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
}
]
解决方案
像这样试试。
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)
推荐阅读
- python - 如何根据多个属性对列表项进行排序,而最后一个优先级是字母?
- javascript - 是否可以用线条或不是矩形的画布制作带有背景的画布?
- python-3.x - 为什么在 python 中使用求和方程只显示 0 个值
- c# - DateTime.ToString(String, IFormatProvider) 不适用于 Xamarin.Forms 中的波斯文 CultureInfo“fa-IR”
- java - Java中使用DAO模式的多对多关系
- r - 如果输入通过,updateTabItems 在模块中不起作用
- c# - 在 chrome C# 中更改下载的文件名
- c# - 使用 Grid 在多列上显示项目
- animation - 有没有办法阻止耀斑动画循环播放?
- ruby-on-rails - 对话迁移 Ruby on Rails