使用 Javascript 从 json 数据动态嵌套 ul\li 列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21140069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamic nested ul\li list from json data using Javascript
提问by user2960708
I need to create a dynamic nested ul\li list from json array.
我需要从 json 数组创建一个动态嵌套的 ul\li 列表。
NOTE!I can do that transformation my self using jQuery, but in this case i need to work with a string, since it's node.js and i don't have access to DOM.
笔记!我可以使用 jQuery 自己进行这种转换,但在这种情况下,我需要使用字符串,因为它是 node.js 并且我无权访问 DOM。
Also the array can have different depth.
数组也可以有不同的深度。
This is json data i work with and how it should look after transformation.
这是我使用的 json 数据以及它在转换后应该如何处理。
var data = [{"id": "1", "name": "name_1", "parent_id": "0", "depth": "0"},
{"id": "2", "name": "name_2", "parent_id": "0", "depth": "0"},
{"id": "3", "name": "name_3", "parent_id": "1", "depth": "1"},
{"id": "4", "name": "name_4", "parent_id": "3", "depth": "2"}];
<ul>
<li>name_1</li> //depth 0
<li>name_2 //depth 0
<ul>
<li>name_3 //depth 1
<ul>
<li>name_3</li> //depth 2
</ul>
</li>
</ul>
</li>
</ul>
I hope this is clear. If not please ask any questions in the comment. Thank you in advanced.
我希望这很清楚。如果没有,请在评论中提出任何问题。先谢谢了。
回答by Dalorzo
Try this:
试试这个:
var data = [{"id": "1", "name": "name_1", "parent_id": "0", "depth": "0"},
{"id": "2", "name": "name_2", "parent_id": "0", "depth": "0"},
{"id": "3", "name": "name_3", "parent_id": "1", "depth": "1"},
{"id": "4", "name": "name_4", "parent_id": "3", "depth": "2"}];
var initLevel = 0;
var endMenu =getMenu("0");
function getMenu( parentID ){
return data.filter(function(node){ return ( node.parent_id === parentID ) ; }).map(function(node){
var exists = data.some(function(childNode){ return childNode.parent_id === node.id; });
var subMenu = (exists) ? '<ul>'+ getMenu(node.id).join('') + '</ul>' : "";
return '<li>'+node.name + subMenu + '</li>' ;
});
}
console.log( '<ul>'+endMenu.join('')+ '</ul>');
However, I think the correct output based on your data will be something like:
但是,我认为基于您的数据的正确输出将类似于:
<ul>
<li>name_1
<ul>
<li>name_3
<ul>
<li>name_4</li>
</ul>
</li>
</ul>
</li>
<li>name_2</li>
</ul>
Here is the JSFiddle sample
Updated Version:
更新后的版本:
回答by Kerstomaat
回答by Erex
If i understand the question correctly you are trying to genereat a list in html from a array of objects.
如果我正确理解了这个问题,您将尝试从对象数组中生成 html 中的列表。
So if your not using JQuery, probably one of these will help you out:
因此,如果您不使用 JQuery,其中之一可能会对您有所帮助:
And if your using JQuery, probably this will help you out:
如果您使用 JQuery,这可能会对您有所帮助: