0

I am trying to loop through a nested object, but I keep returning undefined.

My object:

var ltColumns = {

"col1": {data: "productCode", title: "Product Code", width: "7%" },

"col2": {data: "brand", title: "Brand", width: "5%"}
};

My loop:

for (var key in ltColumns) {
  console.log(key.data);
}

In this case, I am trying to console log the "data" attribute of each nested object. However, I keep getting 'undefined'. Can someone help?

Thanks!

Trung Tran
  • 11,579
  • 39
  • 105
  • 187

3 Answers3

2

Change your loop to:

for (var key in ltColumns) {
    console.log(ltColumns[key].data);
}

jsFiddle example

Your for...in loop returns a property name on each iteration to key, here col1 and col2. So the statement key.data by itself would return undefined because neither col1 nor col2 are an object -- they're properties of ltColumns. So you need to use key and ltColumns together to get the value of the col1 and col2 properties since ltColumns is the actual object.

j08691
  • 197,815
  • 30
  • 248
  • 265
2

Use this:

    console.log(ltColumns[key].data);
nurdyguy
  • 2,774
  • 3
  • 24
  • 30
0
for (var key in ltColumns) {
   console.log(key.data); // key is just a string, not the property itself
                          // "col1".data, "col2".data, etc. 
                          // and these strings do not have `data` property
}

You want to access the properties. Hence object[property] since the dot notation is not possible.

Community
  • 1
  • 1
Vidul
  • 9,616
  • 2
  • 17
  • 20