简体   繁体   English

遍历javascript嵌套对象返回未定义

[英]Looping through javascript nested object returning undefined

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! 谢谢!

Change your loop to: 将循环更改为:

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

jsFiddle example jsFiddle示例

Your for...in loop returns a property name on each iteration to key , here col1 and col2 . 您的for...in循环在每次迭代for...in属性名称返回给key ,此处为col1col2 So the statement key.data by itself would return undefined because neither col1 nor col2 are an object -- they're properties of ltColumns . 因此,由于col1col2都不是对象,因此语句key.data本身将返回未定义状态-它们是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. 因此,由于ltColumns是实际对象,因此您需要一起使用keyltColumns来获取col1col2属性的值。

用这个:

    console.log(ltColumns[key].data);
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. 由于点符号是不可能的,因此是object[property]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM