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);
}
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.
用这个:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.