TheRealPapa TheRealPapa - 2 months ago 15
JSON Question

JSON element pushing into array in Javascript

I am looking to access a HTML element's data (a JSON record) and push it into an array in JavaScript.

The HTML is:

<td class="card-holder" data-card="{"id":0,"type":"Wildcard","image":"wildcard.png","strength":0,"type_image":"wildcard.png","region_owned_adder":0}">
<img id="card-image-0" src="/img/wildcard.png" class="card-exchange">
<input class="cards-checkbox" type="checkbox" id="card-0" name="cards_to_exchange[]" value="id=" 0""="">
<label for="cards_to_exchange"></label>
</td>


I have a number of these on my page. I read each in a loop and select some to push into an array like this:

var cards = [];
$('.card-exchange').each(function() {
if ($(this).find('input[name="cards_to_exchange[]"]').is(':checked')) {
var parseCard = JSON.parse(thisElement.data('card'));
cards.push(parseCard);
}
});


But this is showing me
[]
after the loop:

console.log(cards);


This shows the data OK:

console.log(thisElement.data('card'));


How do I read the string and push it into array as object? Thanks.

Answer Source

You're using .find() on an <img>, which has no descendants.

Use .next() instead to get its <input> sibling.


Also, you can use .filter() and then .map() to clean it up a little.

var cards = $('.card-exchange').filter(function() {
    return $(this).next().is(':checked');
}).map(function() {
    return JSON.parse(thisElement.data('card'));
}).toArray();

Though I'm not sure what thisElement is referring to.


You could even shorten it a little more.

var cards = $('.card-exchange + input:checked')
  .prev()
  .map(function() {
     return JSON.parse(thisElement.data('card'));
  });