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

Community
  • 1
  • 1
Jacob
  • 3,580
  • 22
  • 82
  • 146

2 Answers2

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/

Jeff Shaver
  • 3,315
  • 18
  • 19
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]);
    }
}
Graham
  • 6,484
  • 2
  • 35
  • 39