1

像这样考虑json对象

var data = {
   keyA: [ {keyA0: [keyA00]} ],
   keyB: [ {keyB0: [keyB00]} ]
}

更直观地看起来像这样

-keyA
  - keyA0
      - keyA00
-keyB
  - keyB0
      - keyB00

需要将其转换为类似的东西

var convertedData = {
   name: root
   children:[
              {name:keyA, children: [ {name: keyA0 : children: [{name:keyA0, children: []}]} ]},
              {name:keyB, children: [...]}
            ] 
}

"..." 是递归结构,直到它遇到子节点为空数组的叶节点。

4

1 回答 1

0

解决了它,也许它会被其他有类似问题的人使用。这里是 js 小提琴,http://jsfiddle.net/tF3uH/20/,并进一步参考代码

var data = {
    "KeyA": ["KeyA0", "KeyA1"],
    "KeyB": [{"KeyB0": ["KeyB00", "KeyB01"]}] 
};
/* EXPECTED OUTPUT
[
{name: KeyA: children:[{name:KeyA0, children:[]},
                       {name:keyA1, children:[]}
                      ]
},
{name: KeyB: children:[{name:KeyB0, children: [{name:KeyB00, children: []},
                                               {name:KeyB01, children: []}
                                              ]
                       }
                      ]
}
]
*/
function _doConversion(jsonData, treeList) {    
    if (typeof jsonData == typeof Object()) {
        $.each(jsonData, function(key, val) {
            var isArray = Array.isArray(val);
            var name = key;
            var children = [];
            if (isArray) {
                $.each(val, function(i, item) {
                    _doConversion(item, children);
                });
            }else{ //not array but object
                _doConversion(val,children);
            }
            treeList.push({
                name : name ,
                children: children
            });
        });
    } else { //a leaf (could be string,number,boolean...)
        var node = {
            name: jsonData,
            children: []
        };
        treeList.push(node);
    }
}

var list = [];
_doConversion(data, list);
$("body").text(JSON.stringify(list, null, "\n"));​
于 2012-11-13T18:29:34.723 回答