1

I have 3 button elements on which I have assigned the same type of JSON objects to a data attribute. I imagined that I would be able to get those objects into an array, but I only get a single object from the first match.

Here is my jQuery:

var configs = $("button[id*='alertbtn']").data('config');

I have verified that my selector

$("button[id*='alertbtn']")

targets the correct three elements.

Is it possible to achive what I want using a single line of code?

1 Answer 1

1

One line? Yes. One function call? No. :-)

var configs = $("button[id*='alertbtn']").map(function() { return $(this).data('config'); }).get();

More readably:

var configs = $("button[id*='alertbtn']")
                .map(function() { return $(this).data('config'); })
                .get();

That uses map to get the set of config objects, then get to get the jQuery set's contents as an array.


It's one readable line in ES2015 and above:

let configs = Array.from($("button[id*='alertbtn']")).map(e = > $(e).data('config'));
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.