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!

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Use this:

    console.log(ltColumns[key].data);

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.