开发者

How to convert a tree to a JSON object?

I have this tree and i like to convert it to JSON to use it in jquery option tree.

NodeId, Title, Level
1, cars, 0
2, boats, 0
3, oldtimer, 1
4, trucks, 1
5, heavytrucks, 4

The tree should look like this:

boats
cars
- oldtimer
- trucks
-- heavytrucks

each item has a id.

How can i convert this to JSON?

This example will be given in jquery option tree:

var option_tree = {
    "Option 1": {
        "Suboption": 200
    },
    "Option 2": {
        "Suboption 2": {
            "Subsub 1": 2开发者_开发技巧01,
            "Subsub 2": 202
        },
        "Suboption 3": {
            "Subsub 3": 203,
            "Subsub 4": 204,
            "Subsub 5": 205
        }
    }
};

But Option 1 don't have an id, it has only child elements.


This piece of code will convert your input into a tree

var lines = 
   ('1, cars, 0\n' +
    '2, boats, 0\n' +
    '3, oldtimer, 1\n' +
    '4, trucks, 1\n' +
    '5, heavytrucks, 4').split('\n');

var tree = [];
var lookup = {}; // temporary variable

for (var i in lines) {
    var items = lines[i].split(', ');

    var obj = { id: items[0], parent_id: items[2], name: items[1], children: [] };
    lookup[obj.id] = obj;

    if (lookup[obj.parent_id]) {
        lookup[obj.parent_id].children.push(obj);
    } else {
        tree.push(obj);
    }
}

console.log(tree); // will display your tree

Then you can traverse your tree and modify it how you want it to look.

For example, this will print it

function walk(root, depth) {
    var s = ""; for (var i = 0; i < depth; i++) s += '-';
    console.log(s + ' ' + root.name);
    for (var child in root.children) {
        walk(root.children[child], depth+1);
    }
}

for (var child in tree)
    walk(tree[child], 1);

like this

- cars
-- oldtimer
-- trucks
--- heavytrucks
- boats

You can similarly convert it to whatever you want.

function walk2(root, parent) {
    if (root.children.length == 0) {
        parent[root.name] = root.id;
    } else {
        parent[root.name] = {}
        for (var child in root.children) {
            walk2(root.children[child], parent[root.name]);
        }
    }
}

var tree2 = {};

for (var child in tree)
    walk2(tree[child], tree2);

console.log(tree2); // <- is this what you wanted?
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜