我们希望根据父链接和显示顺序将以下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}]
是否已有其他图书馆或任何简单的方法
答案 0 :(得分:0)
虽然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; }