[英]Javascript - JSON: building a hierarchical tree
I'm trying to display a tree using dhtmlxtreegrid 我正在尝试使用dhtmlxtreegrid显示树
I need help with creating the hierarchical tree data from flattened JSON. 我需要有关从扁平化JSON创建分层树数据的帮助。
My JSON data looks like this: 我的JSON数据如下所示:
{
"rows": [
{
"id": "01", // child id
"parentid": "00", // parent Id
"data": [
"101831",
"Work",
"Desc-4-1"
]
},
{
"id": "02",
"parentid": "01",
"data": [
"101832",
"No Work",
"Desc-4-0"
]
},
{
"id": "03",
"parentid": "01",
"data": [
"101835",
"Work",
"Desc-5-0"
]
},
{
"id": "04",
"parentid": "03",
"data": [
"101835",
"Work",
"Desc-5-1"
]
}
]
}
The Result JSON should be in hierarchical tree structure: 结果JSON应该采用分层树结构:
{
"rows": [
{
"id": "01",
"parentid": "00",
"data": [
"101831",
"Work",
"Desc-4-1"
],
"rows": [
{
"id": "02",
"parentid": "01",
"data": [
"101832",
"No Work",
"Desc-4-0"
]
},
{
"id": "0",
"parentid": "01",
"data": [
"101835",
"Work",
"Desc-5-0"
]
}
]
}
]
}
if you need ac# solution here is a link which generate c# code for you. 如果您需要ac#解决方案,请点击以下链接为您生成c#代码。
http://json2csharp.com/ http://json2csharp.com/
depending your result JSON data here is the c# code : 根据您的结果JSON数据,这里是c#代码:
public class Row2
{
public string id { get; set; }
public string parentid { get; set; }
public List<string> data { get; set; }
}
public class Row
{
public string id { get; set; }
public string parentid { get; set; }
public List<string> data { get; set; }
public List<Row2> rows { get; set; }
}
public class RootObject
{
public List<Row> rows { get; set; }
}
I have tried multiple things I got this working if I understood your problem properly. 如果我正确理解了您的问题,我已经尝试了多种方法来解决这个问题。
Your JSON data:- 您的JSON数据:-
var data = {
"rows": [
{
"id": "01", // child id
"parentid": "00", // parent Id
"data": [
"101831",
"Work",
"Desc-4-1"
]
},
{
"id": "02",
"parentid": "01",
"data": [
"101832",
"No Work",
"Desc-4-0"
]
},
{
"id": "03",
"parentid": "01",
"data": [
"101835",
"Work",
"Desc-5-0"
]
}
]
}
Functions to change the structure. 改变结构的功能。
var addRowsToLastChild = function(obj1,rowsToAppend){
//if that object has rows key check in that row otherwise add rows to the object
if(obj1["rows"]){
addRowsToLastChild(obj1["rows"][0],rowsToAppend);
return;
}
obj1["rows"] = [];
obj1["rows"][0] = rowsToAppend;
obj1;
}
var resultJSON = data.rows.reduce(function(obj1,obj2){
addRowsToLastChild(obj1,obj2);
// object are passed by refference so any changes in obj1 will be affected
return obj1;
},{});
The result will be:- 结果将是:-
{
"rows": [
{
"id": "01",
"parentid": "00",
"data": [
"101831",
"Work",
"Desc-4-1"
],
"rows": [
{
"id": "02",
"parentid": "01",
"data": [
"101832",
"No Work",
"Desc-4-0"
],
"rows": [{
"id": "03",
"parentid": "01",
"data": [
"101835",
"Work",
"Desc-5-0"
]
}
]
}
]
}
]
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.