我计划在 MongoDB 中使用物化路径来表示树,并且需要将物化路径转换回 JSON 树。
前任。//物化路径
var input = [
{"id": "0", "path": "javascript" },
{"id": "1", "path": "javascript/database" },
{"id": "2", "path": "javascript/database/tree" },
{"id": "3", "path": "javascript/mvc" },
{"id": "4", "path": "javascript/mvc/knockout.js"},
{"id": "5", "path": "javascript/mvc/backbone.js"},
{"id": "6", "path": "c++" },
{"id": "7", "path": "c++/c0xx"},
{"id": "8", "path": "c++/c0xx/lambda expressions"},
{"id": "9", "path": "c++/c0xx/vc10" }
];
结果将是:
[
{
"id": "0",
"name": "javascript",
"children": [
{
"id": "1",
"name": "database",
"children": [
{
"id": "2",
"name": "tree",
"children": []
}
]
},
{
"id": "3",
"name": "mvc",
"children": [
{
"id": "4",
"name": "knockout.js",
"children": []
},
{
"id": "5",
"name": "backbone.js",
"children": []
}
]
}
]
},
{
"id": "6",
"name": "c++",
"children": [
{
"id": "7",
"name": "c0xx",
"children": [
{
"id": "8",
"name": "lambda expressions",
"children": []
},
{
"id": "9",
"name": "vc10",
"children": []
}
]
}
]
}
]
我发现使用 JQuery 将分隔字符串转换为分层 JSON效果很好。
而且我还从物化路径中找到了构建树,它是用 Ruby 编写的并使用递归。我很感兴趣和好奇地看到它在 Javascript 中实现,并想知道是否有任何人会流利地使用 Ruby 和 Javascript 来重写它。我确实尝试了一个 Ruby 到 JS 的转换器,但结果令人费解。
谢谢,内维尔