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!
3 Answers 3
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]);
}
}
5 Comments
Array.forEach). NEVER use for..in with Arrays.for..in with arrays.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
}
}
Comments
prop is the index of the array, its not the array. obj is the array. So it should be:
console.log(obj[prop]);
Comments
Explore related questions
See similar questions with these tags.
for...inworks differently for objects than it works for arrays?for..infor arrays, but that doesn't mean that it works differently for arrays than it does for objects.