使json父子关系

时间:2018-09-19 17:00:35

标签: jquery json performance parent-child

我有一个带有父ID的JSON

[{"id":"1","href":"#","text":"ABC","parentid":null},
{"id":"2","href":"#","text":"DEF","parentid":1},
{"id":"3","href":"#","text":"GHI","parentid":2},
{"id":"4","href":"#","text":"JKL","parentid":2}]

现在我正在尝试将其做成这样

enter image description here

通过下面的代码可以成功实现这一目标,但是我认为使用更好的方法可以使其更加完善。我的方法只能用于两个级别,但是我一直在寻找n个级别。有人可以帮我吗?

data.d.results.map(function(item, i) {
        delete item['__metadata']
        var label = item.Title
        var parentid = item.ParentMenuId
        var id = item.Id
        var url = item.Link

        var _item = { id: id, href: url, text: label, children: [] }
        if (!parentid) {
          source.push(_item)
        } else {
          var chd = true
          for (var i = 0; i < source.length; i++) {
            if (source[i]["id"] == parentid) {
              source[i]["children"].push(_item)
              chd = false
              break
            }
          }
          if (chd == true) {
            for (var i = 0; i < source.length; i++) {
              if (source[i]["children"].length > 0) {
                for (var j = 0; j < source[i]["children"].length; j++) {
                  if (source[i]["children"][j]["id"] == parentid) {
                    source[i]["children"][j]["children"].push(_item)
                    break
                  }
                }
              }
            }
          }
        }
      })

0 个答案:

没有答案