【问题标题】:How to populate list and create a Tree-View from JSON Object - JavaScript如何从 JSON 对象填充列表并创建树视图 - JavaScript
【发布时间】:2019-11-04 00:49:49
【问题描述】:

我有一个复杂的 JSON 对象,需要按 parentId 分组。 到目前为止,我在这段代码中实现了我想要的输出:

// My JSON Data
const locations = [
  {
    id: 1,
    name: "San Francisco Bay Area",
    parentId: null
  },
  {
    id: 2,
    name: "San Jose",
    parentId: 3
  },
  {
    id: 3,
    name: "South Bay",
    parentId: 1
  },
  {
    id: 4,
    name: "San Francisco",
    parentId: 1
  },
  {
    id: 5,
    name: "Manhattan",
    parentId: 6
  },
];
function createTreeView(location) {
  var tree = [],
    object = {},
    parent,
    child;

  for (var i = 0; i < location.length; i++) {
    parent = location[i];

    object[parent.id] = parent;
    object[parent.id]["children"] = [];
  }

  for (var id in object) {
    if (object.hasOwnProperty(id)) {
      child = object[id];

      if (child.parentId) {
        object[child["parentId"]]["children"].push(child);
      } else {
        tree.push(child);
      }
    }
  }
  return tree;
}

我只是将其显示为纯 JSON 数据,使用

var root = createTreeView(locations);
document.body.innerHTML = "<pre>" + JSON.stringify(root, null, " ");

是否可以使用上面的代码将此 JSON 数据放入 &lt;li&gt;

【问题讨论】:

  • 你能展示一个你想要的最终 html 应该是什么样子的示例吗?
  • 所以您想将您的树显示为嵌套的&lt;ul&gt;&lt;li&gt; 元素?目前还不够清楚是什么问题。顺便说一句,我尝试将您的 createTreeView 函数与给定的 locations 数组一起使用,但它引发了错误。
  • @nickzoum 这是我想要实现的示例 HTML:imgur.com/31mHGl6>

标签: javascript html arrays json


【解决方案1】:

在这里,我举了一个例子。 查看CreateUlTreeView 并确保您阅读了评论。

// My JSON Data
const locations = [
  {
    id: 1,
    name: "San Francisco Bay Area",
    parentId: null
  },
  {
    id: 2,
    name: "San Jose",
    parentId: 3
  },
  {
    id: 3,
    name: "South Bay",
    parentId: 1
  },
  {
    id: 4,
    name: "San Francisco",
    parentId: 1
  },
  {
    id: 5,
    name: "Manhattan",
    parentId: 6
  },
];
function createTreeView(location) {
  var tree = [],
    object = {},
    parent,
    child;

  for (var i = 0; i < location.length; i++) {
    parent = location[i];

    object[parent.id] = parent;
    object[parent.id]["children"] = [];
  }

  for (var id in object) {
    if (object.hasOwnProperty(id)) {
      child = object[id];
      // i made some changes here incase some element is missing so you dont get error and just append th tree insetad 
      if (child.parentId && object[child["parentId"]]) {
        object[child["parentId"]]["children"].push(child);
      } else {
        tree.push(child);
      }
    }
  }
  return tree;
}


// here is how you build your UL treeview recursively
function CreateUlTreeView(items, parent){
var ul = document.createElement("ul");
if (parent)
    parent.appendChild(ul);
    items.forEach(function(x) {
      var li = document.createElement("li");
      var text = document.createElement("span");
      text.innerHTML = x.name;
      li.appendChild(text);
      if (x.children && x.children.length>0)
         CreateUlTreeView(x.children, li);
      ul.append(li);
    });
    return ul;
}
var root = createTreeView(locations);

CreateUlTreeView(root,document.getElementById("container"))
<div id="container">

</div>

【讨论】:

    【解决方案2】:

    这是一个非常抽象的解决方案。你可以很容易地重复使用。

    触发整棵树的部分是:

    // <LIST>.toTree(<FUNCTION TO GET ID>, <FUNCTION TO GET PARENT ID>);
    var tree = locations.toTree(location => location.id, location => location.parentId);
    // createTreeView(<TREE>, <FUNCTION TO GET NAME>);
    document.body.appendChild(createTreeView(tree, location => location.name)).id = "myUL";
    

    Object.defineProperty(Array.prototype, "toTree", {
      configurable: false,
      writable: false,
      value: function(getKey, getParentKey) {
        var list = JSON.parse(JSON.stringify(this));
        var root = {};
        for (var index = 0; index < list.length; index++) {
          var parentKey = getParentKey.call(list, list[index], index, list);
          var parent = (list.find(function(item, index) {
            return parentKey === getKey.call(list, item, index, list);
          }) || root);
          (parent.children = parent.children || []).push(list[index]);
        }
        return root.children || [];
      }
    });
    
    const locations = [{
      id: 1,
      name: "San Francisco Bay Area",
      parentId: null
    }, {
      id: 2,
      name: "San Jose",
      parentId: 3
    }, {
      id: 3,
      name: "South Bay",
      parentId: 1
    }, {
      id: 4,
      name: "San Francisco",
      parentId: 1
    }, {
      id: 5,
      name: "Manhattan",
      parentId: 6
    }, ];
    
    function createTreeView(tree, getName) {
      var listDom = document.createElement("ul");
      tree.forEach(function(item) {
        var itemDom = listDom.appendChild(document.createElement("li"));
        if (item.children && item.children.length) {
          var itemName = itemDom.appendChild(document.createElement("span"));
          itemName.textContent = getName.call(item, item);
          itemName.className = "caret";
          var nestedList = itemDom.appendChild(createTreeView(item.children, getName));
          nestedList.className = "nested";
        } else {
          itemDom.textContent = getName.call(item, item);
        }
      });
      return listDom;
    }
    
    var tree = locations.toTree(location => location.id, location => location.parentId);
    document.body.appendChild(createTreeView(tree, location => location.name)).id = "myUL";

    【讨论】:

      猜你喜欢
      • 2013-04-27
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多