大家好我希望你能帮我解决这个问题。我的 JSON
文件的结构如下:
[{
{
"link": {
"title": "Applications"
},
"has_children": true,
"subtree": [{
"link": {
"title": "Projects"
},
"subtree": [{
"link": {
"title": "WORK\/NEW YORK",
}
}]
}]
}
}]
基本上它是一个导航菜单,它应该是这样的:
Application => Projects => WORK/NEW YORK
我正在遍历整个 JSON 文件以获取所有第一个对象。我已经设法访问第一个对象并使用以下代码显示“应用程序”:
for (var i = 0; i < list.length; i++) {
var _title = (list[i].link.title);
console.log(_title);
buildingMenuContent(_title);
}
现在,我想遍历第一个数组索引 [0] 并访问其子树第一个索引 [0],最后访问最后一个子树及其索引 [0],这样我就可以显示:
Application => Projects => WORK/NEW YORK
我使用这段代码让我进入应用程序 => 项目,但它没有迭代以获取所有第一个对象:
for (var i = 0; i < list.length; i++) {
if (list[i].has_children) {
for (var n = 0; n < list[i].subtree.length; n++) {
var _subtitle = (list[i].subtree[n].link.title);
}
}
}
}
我不知道我是否澄清了这一点,但我需要遍历这个数组。我使用了一个递归的 for 循环,但是使用它来操作 DOM 太复杂了。
最佳答案
作为一般建议,如果您想要递归迭代它们,请保持 JSON 中对象/节点的模式相似。它将使您的代码变得简单和通用。
不建议像其他人所说的那样为每个级别手动执行此操作。如果另一个级别以第 4 子树的形式出现怎么办?第 5 个子树?你会继续为此编写代码吗?我不这么认为。最好为这种情况提出递归解决方案。为此,对象应该具有相似的结构,以便您可以迭代它们,独立处理每个对象/节点。
// Menu JSON structure
var menuList = [
{
"link": { "title": "Applications" },
"has_children": true,
"subtree": [
{
"link": { "title": "Projects" },
"subtree": [
{
"link": { "title": "WORK\/NEW YORK" }
}
]
}
]
},
{
"link": { "title": "Operations" },
"has_children": true,
"subtree": [
{
"link": { "title": "Projects" },
"subtree": [
{
"link": { "title": "WORK\/DALLAS" }
}
]
}
]
}
];
function printTree(list, isTopLevel) {
let path = '';
// Iterate all the nodes in the provided list array
for ( var i = 0; i < list.length; ++i ) {
path += list[i].link.title;
// Process subtree if present
// This condition can also be based on `has_children` property but since that isn't present across all nodes, I've used `subtree`
if ( list[i].subtree && list[i].subtree.length > 0 ) {
path += '=>'; // Add => only if current node has subtrees
path += printTree(list[i].subtree, false); // Recursively add the subtree paths
}
// Only needed to insert new line after every parent node path has been added
// Not really necessary
if ( isTopLevel )
path += '\n';
}
return path; // Return the path constructed at every node level
}
console.log(printTree(menuList, true));
// Output:
// Applications=>Projects=>WORK/NEW YORK
// Operations=>Projects=>WORK/DALLAS
注意 subtree
属性的使用,它存在于所有节点/对象中。它可用于检测递归情况,因为它存在于所有节点中。
关于javascript - 访问 jSON 文件中的子树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50368242/