Mr. Blonde
Mr. Blonde

Reputation: 721

Collect multiple json objects from data attribute

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?

Upvotes: 1

Views: 59

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074445

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'));

Upvotes: 1

Related Questions