Reputation: 366
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!
Upvotes: 1
Views: 262
Reputation: 16068
prop
is the index of the array, its not the array. obj
is the array. So it should be:
console.log(obj[prop]);
Upvotes: 1
Reputation: 1600
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
}
}
Upvotes: 1
Reputation: 239473
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]);
}
}
Upvotes: 1