F
F
ff0xff2020-01-21 15:28:55
JavaScript
ff0xff, 2020-01-21 15:28:55

How to recursively build a list of uls?

It is necessary to form a ul list from an n dimensional array, I have been picking this code for a long time, but the process has come to a standstill - can someone look with a fresh look and tell me how to do it?

Actually this is the structure:

[
  {
    "id": 1,
    "parent_id": null,
    "children": [
      {
        "id": 2,
        "parent_id": 1,
        "children": []
      },
      {
        "id": 3,
        "parent_id": 1,
        "children": [
          {
            "id": 4,
            "parent_id": 3,
            "children": []
          }
        ]
      }
    ]
  }
]

I want to generate output like this html'ku:
<ul id="organisation">
        <li>1
            <ul>
                <li>2</li>
                <li>3
                         <ul>
                              <li>4</li>
                    </ul>
                  </li>
            </ul>
        </li>
    </ul>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twobomb, 2020-01-21
@ff0xff

var arr1 = [{
  "id": 1,
  "parent_id": null,
  "children": [{
      "id": 2,
      "parent_id": 1,
      "children": []
    },
    {
      "id": 3,
      "parent_id": 1,
      "children": [{
        "id": 4,
        "parent_id": 3,
        "children": []
      }]
    }
  ]
}];

recBuild(document.querySelector("#organisation"),arr1);

function recBuild(parentUl,arr){
  arr.forEach((el)=>{
  	var li = document.createElement("li");
    li.innerHTML = el.id;
    if(el.children.length > 0 ){    
      var ul = document.createElement("ul");
    	recBuild(ul,el.children);
      li.append(ul);
     }
    parentUl.appendChild(li);    
  });
}

<ul id="organisation"></ul>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question