如何解决Json - 树数据格式
我正在尝试格式化 json reposnse 以使其适用于 JStree
这里是 url json 响应
{
"items": [
{ "id": 1,"parent_id": 0,"name": "Root Catalog" },{ "id": 2,"parent_id": 1,"name": "Default Category" },{ "id": 3,"parent_id": 2,"name": "category1" },{ "id": 5,"parent_id": 3,"name": "Sub1_category1" },{ "id": 6,"name": "Sub2_category1" },{ "id": 11,"name": "category2" },{ "id": 12,"name": "category3" },{ "id": 14,"parent_id": 12,"name": "Sub1_category3" },{ "id": 15,"name": "Sub1_category4" }
]
}
这是我想要得到的回应:
[
{ 'id': '1','parent': '#','text': 'Root Catalog' },{ 'id': '2','parent': '1','text': 'Default Category' },{ 'id': '3','parent': '2','text': 'category1' },{ 'id': '5','parent': '3','text': 'Sub1_category1' },{ 'id': '6','text': 'Sub2_category1' },{ 'id': '11','text': 'category2' },{ 'id': '12','text': 'category3' },{ 'id': '14','parent': '12','text': 'Sub1_category3' },{ 'id': '15','text': 'Sub2_category3' },]
这是我的看法:
let test = {
"items": [
{ "id": 1,"name": "Sub1_category4" }
]
}
function formatData(itemsList) {
let formatOutput = [];
for (item of itemsList.items) {
if (item.parent_id > 0) {
if (item.parent_id !== 1 && typeof formatOutput[item.parent_id] === 'undefined') {
formatOutput[item.parent_id] = {
"parent": item.parent_id,"id": item.id,"text": null,"children": [
{
id: item.id,text: item.name,parent: item.parent_id
}
]
}
} else if (item.parent_id !== 1) {
formatOutput[item.parent_id].children.push({
id: item.id,parent: item.parent_id
})
}
}
}
for (item of itemsList.items) {
if (typeof formatOutput[item.id] === 'object') {
formatOutput[item.id].text = item.name
}
}
return formatOutput.filter(val => val)
}
console.log(formatData(test))
2 个问题:
1.Json 未格式化为 jstree 要求
- 键“id”和“parent”的值没有被字符串化
非常感谢您能提供的任何帮助。
解决方法
我无法理解您的所有逻辑,但我希望此代码可以帮助您。
const test = {"items":[
{"id":1,"parent_id":0,"name":"Root Catalog"},{"id":2,"parent_id":1,"name":"Default Category"},{"id":3,"parent_id":2,"name":"category1"},{"id":5,"parent_id":3,"name":"Sub1_category1"},{"id":6,"name":"Sub2_category1"},{"id":11,"name":"category2"},{"id":12,"name":"category3"},{"id":14,"parent_id":12,"name":"Sub1_category3"},{"id":15,"name":"Sub1_category4"}
]
}
const result = test.items.map(x =>{
return {
id: x.id === 1 ? "#" : x.id,// if the id of the element is 1 put # else x.id
parent: x.parent_id,text: x.name
}
})
console.log(result);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。