Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This question already has an answer here:

I'm using Google Chrome's Console window to try and figure out why I'm not able to loop over an array in javascript.

I have a javascript object called moveResult that looks like this:

enter image description here

I'm trying to loop over the MoveParts in javascript like this:

for (var movePart in moveResult.MoveParts) {
    console.log(movePart.From);
};

I always get undefined instead of the actual value. However, If I try to access the first item explicitly I get what I want, like this:

console.log(moveResult.MoveParts[0].From);

The result of this is "b1".

Why isn't my loop working?

I've also tried a foreach:

moveResult.MoveParts.foreach(function (movePart) {
    console.log(movePart.From);
};
share|improve this question

marked as duplicate by Alexander O'Mara, Alexander, icktoofay Dec 26 '14 at 2:03

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

2 Answers 2

up vote 4 down vote accepted

I'm trying to loop over the MoveParts in javascript like this:

for (var movePart in moveResult.MoveParts) {
    console.log(movePart.From);
};

I always get undefined instead of the actual value.

Don't use for-in to loop through arrays, that's not what it's for. for-in is for looping through object properties. This answer shows various ways to loop through arrays.

The reason your for-in didn't work is that movePart is the key, not the actual entry, so if you were using an object (not an array!) you would have used moveResult.MoveParts[movePart].From.

Your forEach version only failed because:

  1. It's forEach, not foreach. Capitalization matters in JavaScript.

  2. You were missing the closing ) on the function call.

The answer linked above has full examples of forEach and others, but here's how yours should have looked:

    moveResult.MoveParts.forEach(function (movePart) {
    // Capital E -----------^
        console.log(movePart.From);
    });
//   ^---- closing )
share|improve this answer

try

moveResult.MoveParts.map(function (movePart) {
    console.log(movePart.From);
};
share|improve this answer
    
Caution: Array.prototype.map does not exist in older browsers. kangax.github.io/compat-table/es5/#Array.prototype.map –  Halcyon Dec 23 '14 at 18:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.