88willr
88willr

Reputation: 148

Convert nested li to group array

This is the closest I've got...

var myArray = $(".req").map(function() {
    return $(".ans > li").text();
}).get();
console.log(myArray);
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<ul>
  <li class="req">apple
    <ul class="ans">
      <li>apple1</li>
      <li>apple2</li>
    </ul>
  </li>
  <li class="req">banana
    <ul class="ans">
      <li>banana1</li>
      <li>banana2</li>
    </ul>
  </li>
</ul>

The outcome I need:

  [
  apple = ["apple1", "apple2"],
  banana = ["banana1", "banana2"]
  ]

I'm not a coder and can only edit existing codes, been doing some trial and error but still no success... thanks for your help.

Upvotes: 1

Views: 43

Answers (1)

omikes
omikes

Reputation: 8513

You could initialize an empty array object and populate it like this:

var answer = {};
$.each($("li.req"), function() {
    var type = $(this).text().split("\n")[0];
    answer[type] = $(this).find("li").map(function() {
        return $(this).text()
    }).get()
});
console.log(answer)
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<ul>
  <li class="req">apple
    <ul class="ans">
      <li>apple1</li>
      <li>apple2</li>
    </ul>
  </li>
  <li class="req">banana
    <ul class="ans">
      <li>banana1</li>
      <li>banana2</li>
    </ul>
  </li>
</ul>

Upvotes: 1

Related Questions