gpt4 book ai didi

javascript - 将平面 JSON 转换为父子关系结构

转载 作者:行者123 更新时间:2023-11-28 04:00:13 29 4
gpt4 key购买 nike

我们希望根据父链接和显示顺序将下面的 JSON 转换为 TreeView 结构的父子关系。

  1. 如果父链接为空,则为父链接
  2. 如果父链接存在,则应添加为子链接
  3. 项目应根据显示顺序排序
[{
"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}]

是否有任何其他可用的库或任何简单的方法来做到这一点

最佳答案

虽然 TitleParentLink.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; }

关于javascript - 将平面 JSON 转换为父子关系结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47182928/

29 4 0
文章推荐: javascript - 在显示数组的每个值后向
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com