[英]Converting Flat JSON To Parent-Child relational Structure
我们想根据父链接和显示顺序将树下结构将JSON下面转换为父子关系。
[{
"ParentLink":{ },
"Id":1,
"Title":"Home ITSD test new",
"Url":{
"Description":"#",
"Url":"https://technologies.sharepoint.com/"
},
"DisplayOrder":1,
"IsActive":true,
"ID":1},{
"ParentLink":{
},
"Id":2,
"Title":"Link6",
"Url":{
"Description":"#",
"Url":"https://technologies.sharepoint.com/"
},
"DisplayOrder":2,
"IsActive":true,
"ID":2},{"ParentLink":{
"Title":"Link6"
},
"Id":3,
"Title":"link7",
"Url":{
"Description":"#",
"Url":"https://technologies.sharepoint.com/"
},
"DisplayOrder":21,
"IsActive":true,
"ID":3},{
"ParentLink":{
"Title":"Link6"
},"Id":4,
"Title":"link8",
"Url":{
"Description":"#",
"Url":"https://technologies.sharepoint.com/"
},
"DisplayOrder":22,
"IsActive":true,
"ID":4},{
"ParentLink":{
"Title":"link8"
},
"Id":5,
"Title":"link9",
"Url":{
"Description":"#",
"Url":"https://technologies.sharepoint.com/"
},
"DisplayOrder":221,
"IsActive":true,
"ID":5}]
是否有其他可用的库,或者是否有任何简单的方法
虽然Title
和ParentLink.Title
没有匹配的值,但是您可以将这两个值都转换为小写字母,并通过迭代给定的数组使用这两个值生成树,并使用一个对象来分配节点和子级。
对于所需的顺序,我建议事先对数据进行排序,并以节点为生成树的实际顺序。 这比仅对以后的部分进行排序要容易。
只是想知道,为什么数据具有两个id属性?
var data = [{ ParentLink: {}, Id: 1, Title: "Home ITSD test new", Url: { Description: "#", Url: "https://technologies.sharepoint.com/" }, DisplayOrder: 1, IsActive: true, ID: 1 }, { ParentLink: {}, Id: 2, Title: "Link6", Url: { Description: "#", Url: "https://technologies.sharepoint.com/" }, DisplayOrder: 2, IsActive: true, ID: 2 }, { ParentLink: { Title: "Link6" }, Id: 3, Title: "link7", Url: { Description: "#", Url: "https://technologies.sharepoint.com/" }, DisplayOrder: 21, IsActive: true, ID: 3 }, { ParentLink: { Title: "Link6" }, Id: 4, Title: "link8", Url: { Description: "#", Url: "https://technologies.sharepoint.com/" }, DisplayOrder: 22, IsActive: true, ID: 4 }, { ParentLink: { Title: "link8" }, Id: 5, Title: "link9", Url: { Description: "#", Url: "https://technologies.sharepoint.com/" }, DisplayOrder: 221, IsActive: true, ID: 5 }], tree = function (data, root) { var r = [], o = {}; data.forEach(function (a) { var id = a.Title.toLowerCase(), parent = a.ParentLink && a.ParentLink.Title && a.ParentLink.Title.toLowerCase(); a.children = o[id] && o[id].children; o[id] = a; if (parent === root) { r.push(a); } else { o[parent] = o[parent] || {}; o[parent].children = o[parent].children || []; o[parent].children.push(a); } }); return r; }(data, undefined); console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.