简体   繁体   中英

How to make a nested ordered list from array data

I have data like this:

var array = ["a", "b", "c", "d", "e"];

I want this data converted like this:

<ol>
 <li>a</li>
   <ol>
    <li>b</li>
     <ol>
      <li>c</li>
       <ol>
        <li>d</li>
       </ol>
     </ol>
  </ol>

I will try this:

var makeNestedList = () => {
  $.each(array, function(i, el) {
    nested += '<ol>';
    nested += '<li>' + el + '</li>';
    makeNestedList();
    nested += '</ol>';
  });
};

But why is the result empty?

You could use Array#reduceRight and create the most nested node first and then the outer ones.

 var array = ["a", "b", "c", "d", "e"], result = array.reduceRight(function (r, a) { return '<ol><li>' + a + r + '</li></ol>'; }, ''); document.body.innerHTML += result; console.log(result); 

From the outside to inside with nodes.

 var array = ["a", "b", "c", "d", "e"]; array.reduce(function (node, item) { var ol = document.createElement('ol'), li = document.createElement('li'); li.appendChild(document.createTextNode(item)); ol.appendChild(li); node.appendChild(ol); return li; }, document.body); 

You have number of problems in your code. You need to pass input array into function and return something from it. Then you don't need loop inside, since you are using recursion anyway.

Something like this I think will fix it:

 var array = ["a", "b", "c", "d", "e"]; var makeNestedList = (arr) => { let nested = '<ol>' nested += '<li>' + arr[0]; if (arr.length > 1) { nested += makeNestedList(arr.slice(1)); } nested += '</li></ol>'; return nested }; document.body.innerHTML = makeNestedList(array) 

You can use something like this:

Logic

  • loop over array in reverse order.
  • For every item, create a ordered list.
  • Append this list to next list.

 function createOrderedList(items) { var ol = document.createElement('ol'); items.forEach(function(item){ ol.appendChild(createListItem(item)) }) return ol; } function createListItem(item) { var li = document.createElement('li'); li.textContent = item; return li; } var array = ["a", "b", "c", "d", "e"]; var list = array.reduceRight(function(p, c){ var el = createOrderedList([c]); if(p === null) { p = el; } else { el.appendChild(p); } return el; }, null); document.querySelector('.content').appendChild(list); 
 <div class='content'/> 

You can try following, your recursive is not correct.

var arr=[1,2,3];
var nested='';

 var nestIt=function(i){
    if(i==arr.length){
        return "";
    }
    nested += '<ol>';
    nested += '<li>' + arr[i]+ '</li>';
    nestIt(i+1)
    nested += '</ol>';

    return nested
}

nestIt(0);
nested;

it will display result in console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM