1

The following piece of code

var test = [
  {region: 'ap', tl: 'lol'},
  {region: 'ew', tl: 'asd'}
];

for(var i in test) {
  console.log(i.region);
}

just displays twice undefined. What's the problem with an array of objects?

Dean
  • 6,610
  • 6
  • 40
  • 90

5 Answers5

4

for...in allows you to access the keys of the object but doesn't provide the reference to the values.

Thus you get the indexes (0 and 1). You can use those indexes to access the object property.

var test = [
  {region: 'ap', tl: 'lol'},
  {region: 'ew', tl: 'asd'}
];

for(var i in test) {
  console.log(test[i].region);
}

Please Note: Array iteration and for...in

for...in should not be used to iterate over an Array where the index order is important.

You mean to use for...of

The for...of statement creates a loop iterating over iterable objects, including: built-in String, Array, Array-like objects (e.g., arguments or NodeList), TypedArray, Map, Set, and user-defined iterables. It invokes a custom iteration hook with statements to be executed for the value of each distinct property of the object.

var test = [
  {region: 'ap', tl: 'lol'},
  {region: 'ew', tl: 'asd'}
];

for(var i of test) {
  console.log(i.region);
}
Mamun
  • 66,969
  • 9
  • 47
  • 59
3

When you use for(var i in test) then i will be an iterator, meaning its value will be 0,1,2,...n where n is the index of the last element in the array.

So to solve your issue, you will have to use i in conjunction with test array as such

test[i].region

not just

i.region

var test = [
  {region: 'ap', tl: 'lol'},
  {region: 'ew', tl: 'asd'}
];

for(var i in test) {
  console.log(test[i].region);
}
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Ahmad
  • 12,336
  • 6
  • 48
  • 88
0

for...in is used to iterate over properties of an object. Here, for e.g. the properties will be 0, 1, etc.

To iterate over arrays, use for...of

var test = [
  {region: 'ap', tl: 'lol'},
  {region: 'ew', tl: 'asd'}
];

for(var i of test) {
  console.log(i.region);
}
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

For arrays you can use Array.prototype.forEach()

Code:

const test = [
  {region: 'ap', tl: 'lol'},
  {region: 'ew', tl: 'asd'}
];

test.forEach(i => console.log(i.region));
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
0

var test = [
  {region: 'ap', tl: 'lol'},
  {region: 'ew', tl: 'asd'}
];

for(var i in test) {
  console.log(test[i].region);
}
zhangwei
  • 21
  • 4