Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic nested ul\li list from json data using Javascript

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

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.

Also the array can have different depth.

This is json data i work with and how it should look after transformation.

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.

like image 736
user2960708 Avatar asked Jan 15 '14 14:01

user2960708


2 Answers

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:

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

like image 192
Dalorzo Avatar answered Sep 22 '22 01:09

Dalorzo


I'd first convert the flat data to hierarchical json, using something like this, so it's more iterable. Then recursively iterate the JSON and add every element to a string.

like image 21
Kerstomaat Avatar answered Sep 22 '22 01:09

Kerstomaat