【问题标题】:Turn a JSON array of arrays into <ul> and <li> elements将 JSON 数组转换为 <ul> 和 <li> 元素
【发布时间】:2018-11-30 15:26:45
【问题描述】:

我正在 Microsoft Power BI 中创建自定义视觉对象。创建 api 使用 typescript 和 d3 库。我也在用jquery

我正在尝试创建一个层次树,它表示拖入视觉对象的字段。所以树的深度是在运行时决定的,所以它不知道它会有多少层。

我已经设法将我的虚拟数据排列到一个嵌套的 JSON 数组中。

这是我在执行 console.log(finalViewModel) 时从控制台截取的屏幕截图

[{ "text": "France","id": 591, "parent": 0, "identity": {long text},
   "nodes"
        [{"text": "Bread", "id", 478, "parent": 591, "identity: {long text}, 
        "nodes" []}, 
        {"text": "Nocco", "id", 498, "parent": 591, "identity: {long text}, 
        "nodes" []}, 
        {"text": "Red Wine", "id", 718, "parent": 591, "identity: {long 
        text}, 
        "nodes" []}]},
   {"text: "Germany", "id" .....so on and so forth

这是我在控制台中对数据进行 JSON.stringify 时的样子,我也只使用了 2 个字段,所以不会太杂乱。

"identity": {long text},不会这样显示。标识字段用于 Power BI 选择管理器,因此当单击树中的某些内容时,它将呈现为其他视觉对象。 long text 是一个非常长的数组的替代品,该数组包含特定项目标识的信息。

现在问题来了,我想将我的 JSON 数据转换为 ul 和 li 元素。像这样:

 <ul>
    <li>France</li>
    <ul>
        <li>Baguette</li>
        <li>Nocco</li>
        <li>Red Wine</li>
    </ul>
    <li>Germany</li>
</ul>

我在网络上找到了许多解决此类问题的方法,但似乎没有一个能满足我的需求。

谁能帮我提供一个工作代码 sn-p?

提前致谢

【问题讨论】:

    标签: jquery json typescript d3.js powerbi


    【解决方案1】:

    这是一个演示如何使用纯 javascript 实现它。

    var createSublist = function(container, args) {
      var ul = document.createElement('ul');
      
      for(var j = 0; j < args.length; j++) {
        var row = args[j];
        
        var li = document.createElement('li');
        li.innerText = row.text;
        
        var nodes = row.nodes;
        if(nodes && nodes.length) {
          createSublist(li, nodes);
        }
        
        ul.appendChild(li);
      }
      
      container.appendChild(ul);
    };
    
    var data =[  
       {  
          "text":"France",
          "nodes":[  
             {  
                "text":"Bread"
             },
             {  
                "text":"Nocco"     
             }
          ],
    
       },
       {  
          "text":"Italy",
          "nodes":[  
             {  
                "text":"Pizza"
             },
             {  
                "text":"Wine",
                "nodes": [
                  { 
                  	"text": "Red"
                  },
                  { 
                  	"text":"White"
                  }
                ]
             }
          ]
       }
    ];
    
    var container = document.getElementsByClassName('container')[0];  
    if(container) 
    { 
      createSublist(container, data);
    } 
    else 
    {
      console.log('Container has not been found'); 
    }
      
    <div class="container">
    </div>

    【讨论】:

      【解决方案2】:

      JavaScript ES6 和一个小的递归函数

      /**
       * Convert Tree structure to UL>LI and append to Element
       * @syntax getTree(treeArray [, TargetElement [, onLICreatedCallback ]])
       *
       * @param {Array} tree Tree array of nodes
       * @param {Element} el HTMLElement to insert into
       * @param {function} cb Callback function called on every LI creation
       */
      
      const treeToHTML = (tree, el, cb) => el.append(
        tree.reduce((ul, n) => {
          const li = document.createElement("li");
      
          if (cb) cb.call(li, n);
          if (n.nodes?.length) treeToHTML(n.nodes, li, cb);
      
          ul.append(li);
          return ul;
        }, document.createElement("ul"))
      );
      
      
      
      
      
      // DEMO TIME:
      
      const myTree = [{
        "id": 1,
        "parent_id": 0,
        "name": "Item1",
        "nodes": [{
          "id": 2,
          "parent_id": 1,
          "name": "Item2"
        }]
      }, {
        "id": 4,
        "parent_id": 0,
        "name": "Item4",
        "nodes": [{
            "id": 9,
            "parent_id": 4,
            "name": "Item9"
          }, {
            "id": 5,
            "parent_id": 4,
            "name": "Item5",
            "nodes": [{
              "id": 3,
              "parent_id": 5,
              "name": "Item3"
            }]
          }
        ]
      }];
      
      treeToHTML(myTree, document.querySelector("#demo"), function(node) {
        this.textContent = `${node.parent_id} ${node.id} ${node.name}`
      });
      &lt;div id="demo"&gt;&lt;/div&gt;

      【讨论】:

        猜你喜欢
        • 2013-05-26
        • 2023-04-02
        • 1970-01-01
        • 1970-01-01
        • 2012-09-08
        • 1970-01-01
        • 1970-01-01
        • 2019-05-28
        • 1970-01-01
        相关资源
        最近更新 更多