Dan Rubio Dan Rubio - 2 months ago 6
CoffeeScript Question

Why can't I iterate over this array saved on an html data selector with javascript?

I have an html element in haml that looks like this:

= select_tag 'release_version', options_for_select(major_releases(@releases)), include_blank: 'All', style: 'max-width: 30%', data: { releases: @releases }


The
@releases
variable is an active record relation object with a bunch of release objects.

In my coffeefile, I have this code:

$('#release_version').on 'change', ->
selVal = $('#release_version').val()
release_html_selector = document.getElementById('release_version')
release_objects = release_html_selector.dataset.releases
filtered_releases = release_objects.filter((item) ->
///^#{selVal}///.test item.version
)


When the code tries to execute I get this error:


application.js:35397 Uncaught TypeError: release_objects.filter is not a function


When I inspect the elements with
alert
the object looks like this:

[{
"id":398,
"kb_release_id":"vwu3jiwk86",
"released_on":"2009-05-15T00:00:00.000Z",
"version":"2.1.1",
"created_at":"2016-09-15T20:36:42.831Z",
"updated_at":"2016-09-15T20:36:42.831Z"},
{},
{},
etc....]


This is an iterable data structure. Is there something I'm missing here?

Answer

It's possible that the data is actually JSON string not array

Try parsing it as json

release_objects = JSON.parse(release_html_selector.dataset.releases)