4

I have a lot of data stored in associative array.

array = {'key':'value'};

How to loop throught an array like this using an normal for loop and not a loop like here: http://jsfiddle.net/HzLhe/

I don't want to use for-in because of this problems: Mootools when using For(...in Array) problem

7
  • Why don't you like for .. in loop? Commented Apr 4, 2013 at 11:05
  • why not using for..in loop ..? Commented Apr 4, 2013 at 11:05
  • It is messing with Mototools! stackoverflow.com/questions/7034837/… Commented Apr 4, 2013 at 11:06
  • @Jacob that is because you have to use the .hasOwnProperty method to filter out the prototype chains properties Commented Apr 4, 2013 at 11:09
  • @Jacob You are using object and not array. These elements are different in JavaScript. for .. in loop is the best to iterate objects. Commented Apr 4, 2013 at 11:09

2 Answers 2

8

As others have pointed out, this isn't an array. This is a JavaScript object. To iterate over it, you will have to use the for...in loop. But to filter out the other properties, youw ill have to use hasOwnProperty.

Example:

var obj={'key1': 'value1','key2':'value2'};

for (var index in obj) {
    if (!obj.hasOwnProperty(index)) {
        continue;
    }
    console.log(index);
    console.log(obj[index]);
}

http://jsfiddle.net/jeffshaver/HzLhe/3/

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

Comments

4

JavaScript does not have the concept of associative arrays. Instead you simply have an object with enumerable properties, so use a for..in loop to iterate through them. As stated above you may also want to perform a check with hasOwnProperty to ensure that you're not performing operations on inherited properties.

for (var prop in obj){
    if (obj.hasOwnProperty(prop)){
        console.log(obj[prop]);
    }
}

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.