Dynamic ul \ li nested list from json data using javascript

I need to create a dynamic ul \ li nested list from a json array.

NOTE! I can do this conversion myself using jQuery, but in this case I need to work with the string since node.js and I do not have access to the DOM.

Also, the array can have different depths.

This is the json data I'm working with, and how it should look after conversion.

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> 

Hope this is clear. If not, please ask any questions in the comment. Thank you for your promotion.

+8
json javascript arrays html
source share
3 answers

Try the following:

 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 result based on your data would be something like this:

  <ul> <li>name_1 <ul> <li>name_3 <ul> <li>name_4</li> </ul> </li> </ul> </li> <li>name_2</li> </ul> 

Here is a sample JSFiddle

Updated Version:

http://jsfiddle.net/LqES7/47/

+9
source share

First, I would convert flat data into hierarchical json using something like this to make it more iterative. Then iterate over JSON recursively and add each element to the string.

+1
source share

If I understand the question correctly, you are trying to generate a list in html from an array of objects.

So, if you are not using jQuery, perhaps one of them will help you:

  • Create the ul and li elements in javascript.
  • Create a UL and fill it based on the passed array

And if you use jQuery, maybe this will help you:

  • How to generate a UL Li list from an array of strings using jquery?
0
source share

All Articles