0

I need to get a list of values from a set of element attributes and store them in an array.

Currently, I am doing this:

var ids = [];

$("my selector").each(function (idx, v) {

    ids.push($(v).data("id"));
});

This seems a bit clunky. Is there a more efficient/streamlined way of doing this? Perhaps something more like this:

var ids = $("my selector").data("id");

2 Answers 2

6

Try using .map() along with .get() in this context,

var ids = $("my selector").map(function(){
   return $(this).data("id");
}).get();
Sign up to request clarification or add additional context in comments.

Comments

1

Less clunky:

$("my selector").each(function () {
    ids.push($(this).data("id"));
});

By, removing idx and v, you can use $(this)

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.