hollycrab hollycrab - 6 months ago 25
jQuery Question

Convert list of HTML element into Javascript list of object

I'm trying to convert something like this HTML snippet:

<ul>
<li><span>Frank</span><img src="pic.jpg"></li>
<li><span>Steve</span><img src="pic2.jpg"></li>
</ul>


into a JavaScript objects that contain the name and the image's url. How can I do that?

Answer

Use map() method

var res = $('ul li').map(function() { // select all li and iterate
  // return as required format of array elemnt
  return {
    name: $('span', this).text(), // get text in span
    src: $('img', this).attr('src') // get src attribute
  }
}).get(); // get array from jquery object

console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li><span>Frank</span>
    <img src="pic.jpg">
  </li>
  <li><span>Steve</span>
    <img src="pic2.jpg">
  </li>
</ul>


UPDATE : If you want to generate an object which has key as span text and value as src attribute then use each() method and iterate over elements and generate object.

var res = {};
$('ul li').each(function() { // select all li and iterate
  res[$('span', this).text().trim()] = $('img', this).attr('src');
})

console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li><span>Frank</span>
    <img src="pic.jpg">
  </li>
  <li><span>Steve</span>
    <img src="pic2.jpg">
  </li>
</ul>