Home > Software engineering >  Get multidimensional array from ordered list
Get multidimensional array from ordered list

Time:09-19

I have a simple nested list.

<ol id="draggable" >
    <li data-id="1">Lion</li>
    <li data-id="2">Snake</li>
    <li data-id="3">Butterfly
        <ol data-id="3">
            <li data-id="31">Fish</li>
            <li data-id="32">Cat</li>
            <li data-id="33">Monkey</li>
        </ol>
    </li>
    <li data-id="4">Parrot</li>
</ol>

I want to get all IDs of the <li> as a multidimensional array. Therefore I tried to used jQuery's .each(), but that returns only one iteration.

$( "#draggable li" ).each(function( index ) {
    console.log( index   ": "   $( this ).text() );
});

That results in the following output:

0: Lion
1: Snake
2: Butterfly                                                
  Fish
  Cat
  Monkey
3: Fish
4: Cat
5: Monkey
6: Parrot

CodePudding user response:

So, start by making your life a little easier, because text() does what it should, i.e. return the element's full content: add a span around the li's titles, as follows:

<ol id="draggable" >
        <li data-id="1"><span>Lion</span></li>
        <li data-id="2"><span>Snake</span></li>
        <li data-id="3"><span>Butterfly</span>
            <ol data-id="3">
                <li data-id="31"><span>Fish</span></li>
                <li data-id="32"><span>Cat</span></li>
                <li data-id="33"><span>Monkey<span></li>
            </ol>
        </li>
        <li data-id="4"><span>Parrot</span></li>
    </ol>

Then the code goes as follows:

$(document).ready(function(){
    var res = {};
    parse($("#draggable"), res);
    console.log(res);
});

function parse(obj, result) {
    $("li", obj).each(function(index){
        result[index] = {'libelle': $("span", this).first().text(), 'sub': {}};
        parse($("ol", this), result[index]['sub']);
    });
}

Output:

{
  "0": {
    "libelle": "Lion",
    "sub": {}
  },
  "1": {
    "libelle": "Snake",
    "sub": {}
  },
  "2": {
    "libelle": "Butterfly",
    "sub": {
      "0": {
        "libelle": "Fish",
        "sub": {}
      },
      "1": {
        "libelle": "Cat",
        "sub": {}
      },
      "2": {
        "libelle": "Monkey",
        "sub": {}
      }
    }
  },
  "3": {
    "libelle": "Fish",
    "sub": {}
  },
  "4": {
    "libelle": "Cat",
    "sub": {}
  },
  "5": {
    "libelle": "Monkey",
    "sub": {}
  },
  "6": {
    "libelle": "Parrot",
    "sub": {}
  }
}

HTH

  • Related