在树结构中显示json视图

时间:2017-12-04 11:38:23

标签: javascript jquery json angular tree

在树结构中转换以下json

data = {
  "a": {
    "b": [
      {
        "c": "v1",
        "f": [
          "v3",
          "v4"
        ]
      }
    ]
  }
}

实际上我想使用angular2 tree包在树级别显示上面的json,所以预期的输出应该是

nodes = [
  {
    "name": "a",
    "children": [
      {
        "name": "b",
        "children": [
          {
            "name": "c"
          },
          {
            "name": "f",
            "children": [
              {
                "name": "v3"
              },
              {
                "name": "v4"
              }
            ]
          }
        ]
      }
    ]
  }
]

我正在尝试关注但无法在树级别上转换json以上

const getFinalNode = function(data, nodes){
       if (typeof data === 'object'){
       Object.keys(data).forEach(function(key){
          let tmpObj = {
            name: key,
            children: []
          }
          if(typeof key === "object"){
            tmpObj.children = getFinalNode(data[key])
          }
          nodes.push(tmpObj)
        })
       }elseif(data instanceof Array){
        arr.forEach(function(obj, idx){
          let tmpObj = {
            name: obj,
            children: []
          }
          if(data instanceof Array){
            tmpObj.children = getFinalNode(obj.children)
          }
          arr[idx] = tmpObj
        })
        return arr
       }
        return nodes
      }
getFinalNode(data, nodes);

其实我想以下列方式显示json。

enter image description here

0 个答案:

没有答案