Skip to content
Advertisement

get sub object data to array

object data

I have the object from the console like the following

object { 0: div#ch2.group-item, 1: div#ch4.group-item, length: 2 }

I want to convert it to array ids [ch2,ch4]

var ids=$.each(children, function() { return $(this).attr('id'); });
console.log(ids);

Advertisement

Answer

So, you need to use jquery map instead of each.

For example.

const children = $('li');

const result = $.map(children, (item) => item.id)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li id="one">
    first
  </li>
    <li id="two">
    second
  </li>
    <li id="three">
    third
  </li>
    <li id="four">
    fourth
  </li>
    <li id="five">
    fivth
  </li>
</ul>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement