views:

151

answers:

1

Hello,

Sorry if my title is hard to understand. Let me explain.

To use this example of my structure:

Array
(
[2] => Array
    (
        [0] => stdClass Object
            (
                [category_id] => 2
                [category_name] => women
                [project_id] => 1
                [project_name] => Balloons
            )

    )

[1] => Array
    (
        [0] => stdClass Object
            (
                [category_id] => 1
                [category_name] => men
                [project_id] => 2
                [project_name] => Cars
            )

        [1] => stdClass Object
            (
                [category_id] => 1
                [category_name] => men
                [project_id] => 3
                [project_name] => Houses
            )

    )

Then once i have that, i send it out to be eval'd by javascript(which is successful). Console.log does in fact shows that's my eval'd json is in fact now an object.

Now, If i console.log(myArray[2]), it will show it as an array that contains another array. Which is also correct

BUT!.. if i try to do this:

for (item in myArray[2]) {
...
}

or this:

newVar = myArray[2]
for (item in newVar) {
...
}

"item" doesn't contain the array as it should. it contains a string equal the sub arrays' key. Which in this case is "0"

What am I missing here guys? :(

Thanks for the help!

+2  A: 

You already said what the problem was: "item" doesn't contain the array... it contains a string equal the sub arrays' key. So, you just need to use that key:

var subarray;
for (var i in myArray) {
    subarray = myArray[i];
    for (var j in subarray) {
        ... // do stuff with subarray[j]
    }
}
Matt Ball
If you're using JavaScript libraries that might override Array/Object prototypes, you'll also want to check hasOwnProperty: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Global_Objects:Object:hasOwnProperty
Annie
Good point. Additionally, if you're developing for FF only, there is a way to iterate in the way you were trying to before - use `forEach`: https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/ForEach or `for each ... in` : https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for_each...in
Matt Ball
Thanks for the help! It works now. I still have using a single for loop but i'm accessing my values list so: myArray[i]['project_name']
Jeff