簡體   English   中英

將平面JSON轉換為父子關系結構

[英]Converting Flat JSON To Parent-Child relational Structure

我們想根據父鏈接和顯示順序將樹下結構將JSON下面轉換為父子關系。

  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; } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM