1

I have an ajax call that works well in a view, but I would like to make it in a coffee script, right inside a datatable call. The code looks like:

    $(document).ready(function () {
    $.ajax({
      type: "GET",
      url: "<%= people_path(format: :json) %>",
      dataType: "json",
      success: function({data}) {
        const user_ids = data.map(user => user.id)
        $("#people-ids").html(user_ids.join());
      }
    });
  });

I am new to coffeescript, so I need some help to finish the method around the mapping section. I could go as far as this:

ajax:
  type: 'GET'
  url: $('#people-datatable').data('source')
  dataType: 'json'
  success: ({data}) ->

I obtain 7 objects in {data}, but i do not know how to continue to retrieve their ID as in JS. can someone help please ?

2
  • I'm not sure what the issue is--it can be the same as the JS. Commented Sep 22, 2022 at 16:45
  • When i simply put the same as JS I get an error user does not exist in the data.map line Commented Sep 23, 2022 at 1:09

1 Answer 1

1

In the map iterator function you need to wrap the parameter name in parenthesis. Coffeescript doesn't support the syntax without parenthesis which is allowed in javascript.

It would be ambiguous as it could be interpreted as user => ... being a function user being executed with the argument => ...

This should work:

$(document).ready ->
  $.ajax
    type: "GET",
    url: "<%= people_path(format: :json) %>",
    dataType: "json",
    success: ({ data }) ->
      user_ids = data.map (user) -> user.id
      $("#people-ids").html user_ids.join() 

While you are learning the syntax it might be useful to build snippets in http://coffeescript.org/#try: so you can see what it transpiles to instantly.

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

Comments

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.