0

I'm trying to generate a multidimensional array with ul and li ids in jquery to pass it to php file.

<ul id="U1">
<li id="L1"></li>
</ul>
<ul id="U2">
<li id="L2"></li>
<li id="L3"></li>
</ul>
<ul id="U3">
<li id="L4"></li>
<li id="L5"></li>
<li id="L6"></li>
</ul>

var ul_arr = [];
$('ul').each(function () {
var ul_id = $(this).attr('id');
ul_arr.push(ul_id);
var li_arr = [];
$(this).find('li').each(function () {
var li_id = $(this).attr('id');
li_arr.push(li_id);
});
ul_arr[ul_id].push(li_arr);
});

I would like to receive array like this:

[U1 => array[L1], U2 => array[L2, L3], U3 => array[L4, L5, L6]].

I have a problem with setting id as a key in array. It does not work. How to solve this? Thanks in advance!

1 Answer 1

1

You can make use of .map() to transform each subarray of <li> into an array of their IDs:

var uls = {};

$('ul').each(function () {
  uls[$(this).attr('id')] = $(this).find('li').map(function () {
    return $(this).attr('id');
  }).get();
});

console.log(uls);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="U1">
  <li id="L1"></li>
</ul>
<ul id="U2">
  <li id="L2"></li>
  <li id="L3"></li>
</ul>
<ul id="U3">
  <li id="L4"></li>
  <li id="L5"></li>
  <li id="L6"></li>
</ul>

Sign up to request clarification or add additional context in comments.

1 Comment

Works! Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.