json嵌套ul li jquery / javascript

时间:2017-12-05 12:41:40

标签: javascript jquery json

我正在使用拖放构建器中的javascript创建动态json,现在我无法将json转换为Nested Ul li。 json在下面。

[
  {
    "id": "11",
    "name": "BALANCE"
  },
  {
    "id": "p1",
    "name": "Conditions",
    "nodes": [
      {
        "id": "p1-13",
        "name": "SPINAL CORD INJURY",
        "nodes": [
          {
            "id": "p1-13-12",
            "name": "STROKE",
            "nodes": [
              {
                "id": "p1-13-12-17",
                "name": "REACHING"
              }
            ]
          }
        ]
      }
    ]
  },
  {
    "id": "p1-16",
    "name": "STRETCHES"
  },
  {
    "id": "p1-11",
    "name": "BALANCE"
  }
]

1 个答案:

答案 0 :(得分:0)

如果项目中有function,您可以创建nodes并递归调用。



var json = [{"id":"11","name":"BALANCE"},{"id":"p1","name":"Conditions","nodes":[{"id":"p1-13","name":"SPINAL CORD INJURY","nodes":[{"id":"p1-13-12","name":"STROKE","nodes":[{"id":"p1-13-12-17","name":"REACHING"}]}]}]},{"id":"p1-16","name":"STRETCHES"},{"id":"p1-11","name":"BALANCE"}];

function createUl(data, $elm) {
  data.forEach(function(item) {
    var $li = $('<li><span>' + item.name + '</span></li>');
    $elm.append($li);

    if (item.nodes) {
      var $ul = $('<ul></ul>');
      $li.append($ul);
      createUl(item.nodes, $ul);
    }
  });
};

createUl(json, $('ul'));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul></ul>
&#13;
&#13;
&#13;