gpt4 book ai didi

javascript - angular-tree-component json 到可接受的格式并动态创建复选框或单选按钮

转载 作者:行者123 更新时间:2023-11-30 19:43:53 25 4
gpt4 key购买 nike

我有一个使用 angular-tree-component 作为以下链接的 TreeView Refernece

数组格式如下:

nodes = [
{
id: 1,
name: 'root1',
children: [
{ id: 2, name: 'child1' },
{ id: 3, name: 'child2' }
]
},
{
id: 4,
name: 'root2',
children: [
{ id: 5, name: 'child2.1' },
{
id: 6,
name: 'child2.2',
children: [
{ id: 7, name: 'granchild 2.2.1' }
]
}
]
}
];

但我有一个 json 嵌套数组,格式如下:

[
{
"name": "root1",
"subCategory": [
{
"name": "child1",
"childCategory": []
},
{
"name": "child2",
"childCategory": []
}
]
},
{
"name": "level2",
"subCategory": [
{
"name": "level2.1",
"childCategory": []
},
{
"name": "level2.2",
"childCategory": [
{
"name": "granchild 2.2.1",
"type": "checkbox"
}
]
}
]
}
]

我的疑惑如下:

  • 如何将 json 转换为所需的 array angular-tree-component 可接受的格式
  • 如您所见,类型是复选框 {"name": "granchild 2.2.1","type": "checkbox"}。所以孙子 2.2.1 应该是一个复选框,如果它是单选按钮它应该是单选按钮。

请指导我...

最佳答案

您可以使用此代码将 json 转换为您的数组(开始时 id=1)

a.map(x=> (
x.id=id,
id++,
x.subCategory.map(y=> (
y.id=id,
id++,
(y.childCategory.length ? y.children=y.childCategory : 0),
y.childCategory.map(z=> (z.id=id, id++)),
delete y.childCategory
)),
(x.subCategory.length ? x.children=x.subCategory : 0),
delete x.subCategory
));

let a=[
{
"name": "root1",
"subCategory": [
{
"name": "child1",
"childCategory": []
},
{
"name": "child2",
"childCategory": []
}
]
},
{
"name": "level2",
"subCategory": [
{
"name": "level2.1",
"childCategory": []
},
{
"name": "level2.2",
"childCategory": [
{
"name": "granchild 2.2.1",
"type": "checkbox"
}
]
}
]
}
]

let id=1;

a.map(x=> (
x.id=id,
id++,
x.subCategory.map(y=> (
y.id=id,
id++,
(y.childCategory.length ? y.children=y.childCategory : 0),
y.childCategory.map(z=> (z.id=id, id++)),
delete y.childCategory
)),
(x.subCategory.length ? x.children=x.subCategory : 0),
delete x.subCategory
));


console.log(a);

关于javascript - angular-tree-component json 到可接受的格式并动态创建复选框或单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55126038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com