Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through associative array using sequential for loop

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

like image 495
Jacob Avatar asked Dec 16 '22 12:12

Jacob


1 Answers

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/

like image 188
Jeff Shaver Avatar answered Mar 27 '23 10:03

Jeff Shaver