Question

I have the following object:

myObject: {

 myArray1: [1,2,3],
 myArray2: [4,5,6],
 myArray3: [7,8,9]
}

This is an object that keeps growing in Arrays(dynamic array?). So I need to figure out a method to access it. I came across using a for( var key in myObject) with something like this:

    for (var key in myObject) {
     var obj = myObject[key];
       for (var prop in obj) {
           //thinking that this will print the first value of the array
       console.log(prop[0]);
     }
    }

but it doesn't work it prints undefined. I know using a for in is not the way to access an object correctly. I'm wondering if anyone could suggest a method to access the values of this object through a loop.

Thanks!

Was it helpful?

Solution

Iterating an object with for..in is okay, but not an array. Because when you sue for..in with an array, it will not get the array values, but the array indices. So, you should be doing something like this

for (var key in myObject) {
    var currentArray = myObject[key];
    for(var i = 0; i < currentArray.length; i += 1) {
        console.log(currentArray[i]);
    }
}

OTHER TIPS

You made a mistake in 2nd loop. obj is the array and prop is the index

for (var key in myObject) {
  var obj = myObject[key];
   for (var prop in obj) {
       //this will print the first value of the array
   console.log(obj[prop]); //obj is the array and prop is the index
 }
} 

prop is the index of the array, its not the array. obj is the array. So it should be:

console.log(obj[prop]); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top