Here's my code:
obj = {"TIME":123,"DATE":456}
console.log(obj.TIME);
console.log("---------")
for (var key in obj) {
console.log(key);
console.log(obj.key);
}
It prints as the following:
123
---------
TIME
undefined
DATE
undefined
Why does console.log(obj.key) print as undefined?
I want my code to print out the following, using obj.key to print out the value for each key:
123
---------
TIME
123
DATE
456
How do I do so?
Object. key(). It returns the values of all properties in the object as an array. You can then loop through the values array by using any of the array looping methods.
You have to pass the object you want to iterate, and the JavaScript Object. keys() method will return an array comprising all keys or property names. Then, you can iterate through that array and fetch the value of each property utilizing an array looping method such as the JavaScript forEach() loop.
because there is no key in the object with the name 'key'. obj.key
means you are trying to access a key inside obj with the name key. obj.key
is same as obj['key']
you need to use obj[key]
, like this:
obj = {"TIME":123,"DATE":456}
console.log(obj.TIME);
console.log("---------")
for (var key in obj) {
console.log(key);
console.log(obj[key]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With