24

I have a flat json file structure like:

[
 { "name" : "ABC", "parent":"DEF", "relation": "ghi", "depth": 1 },
 { "name" : "DEF", "parent":"null", "relation": "null", "depth": 0 },
 { "name" : "new_name", "parent":"ABC", "relation": "rel", "depth": 2 }
 ....
 ....
 ]

And what I want is a nested file structure like:

[ 
 {
   "name": "DEF",
   "parent": "null",
   "relation": "null",
   "children": [
                 { "name": "ABC",
                   "parent": "DEF",
                   "relation": "ghi",
                   "children": [
                                 "name": "new_name",
                                 ...
                                 "children": []
                               ]
                 }
               ]
  }
 ]

There is no limit on how many levels deep it should go. The current max I have is 30. There is no limit on the number of children a node can have. Eg. The root node has all the remaining as its children.

What I have tried till now?

The source of the data is MS SQL Server database which I am fetching and parsing through python. Kindly help! i have been stuck at this for the past 2 weeks.

Thanks

4

1 に答える 1

45

Javascript での 1 つの実装を次に示します: http://jsfiddle.net/9FqKS/

簡単に検索できる名前ベースのマップを作成することから始めます。これを行うにはいくつかの方法があります。この場合は.reduce、空のオブジェクトから開始してdata配列を反復処理し、各ノードのエントリを追加するメソッドを使用します。

// create a {name: node} map
var dataMap = data.reduce(function(map, node) {
    map[node.name] = node;
    return map;
}, {});

これは次と同等です。

var dataMap = {};
data.forEach(function(node) {
    dataMap[node.name] = node;
});

(reduce の方がエレガントだと思うこともあります。) 次に、各子をその親に繰り返し追加するか、親が見つからない場合はルート配列に追加します。

// create the tree array
var tree = [];
data.forEach(function(node) {
    // find parent
    var parent = dataMap[node.parent];
    if (parent) {
        // create child array if it doesn't exist
        (parent.children || (parent.children = []))
            // add node to parent's child array
            .push(node);
    } else {
        // parent is null or missing
        tree.push(node);
    }
});

ツリーが巨大でない限り、これは高すぎるとは思わないので、クライアント側で実行できるはずです (それができない場合は、データが多すぎていずれにしても簡単に表示できない可能性があります)。 .

于 2013-07-25T05:00:01.740 に答える