0

Is there a short hand notation for iterating through a javascript array that yields the actual object, instead of the index of the object?

For example:

var dataset = ['a','b','c']

for (item in dataset){
    console.log(item);

}

I want to log 'a','b','c' -- not 0,1,2.

My reason for not wanting to use dataset[item] is that I have several nested for loops, and the code is getting very verbose.

3
  • Array.prototype.forEach -- pretty much every lib offers a flavour of this (e.g. $.each, _.each) or use ES6 for .. of .. and transpile Commented Jul 22, 2014 at 14:29
  • for ... in is for objects, not arrays. Commented Jul 22, 2014 at 14:32
  • 1
    Don't use for in loops on arrays! Commented Jul 22, 2014 at 14:32

2 Answers 2

1

If you're willing to use jQuery (which can blend well with basic JS), it's as simple as this:

var dataset = ['a', 'b', 'c'];
$(dataset).each(function (i, o) {
    console.log(o);
});

What this does, essentially, is performs a foreach loop on dataset, treating it like an array containing objects. The index is stored in i and a non-jQuery object is stored in o. You can use $(o) to get the jQuery version of this object.

Hope this helps!

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

Comments

0

Turns out this can be accomplished using the forEach loop:

dataset.forEach(function(item){
    console.log(item);
});

1 Comment

Yep, its going to be sweet when we can do for (x of dataset) {console.log(x)}

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.