如何将树转换为JSON对象?

时间:2011-04-27 13:00:52

标签: javascript json tree option

我有这棵树,我喜欢将它转换为JSON,以便在jquery option tree中使用它。

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

树应如下所示:

boats
cars
- oldtimer
- trucks
-- heavytrucks

每个项目都有一个ID。

如何将此转换为JSON?

此示例将在jquery选项树中给出:

var option_tree = {
    "Option 1": {
        "Suboption": 200
    },
    "Option 2": {
        "Suboption 2": {
            "Subsub 1": 201,
            "Subsub 2": 202
        },
        "Suboption 3": {
            "Subsub 3": 203,
            "Subsub 4": 204,
            "Subsub 5": 205
        }
    }
};

但是选项1没有id,它只有子元素。

也许有人可以提供帮助。

1 个答案:

答案 0 :(得分:2)

这段代码会将您的输入转换为树

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

然后,您可以遍历树并根据需要修改它。

例如,这将打印出来

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);
像这样

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

您可以类似地将其转换为您想要的任何内容。

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?