Iterating through a javascript object to get key-value pairs
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 the following:
123
---------
TIME
undefined
DATE
undefined
Why does console.log (obj.key) print as undefined?
I want my code to print the following, using obj.key to print the value for each key:
123
---------
TIME
123
DATE
456
How should I do it?
+3
source to share
1 answer
because there is no key named "key" in the object. obj.key
means you are trying to access a key inside obj using the name key. obj.key
coincides withobj['key']
you need to use obj[key]
for example:
obj = {"TIME":123,"DATE":456}
console.log(obj.TIME);
console.log("---------")
for (var key in obj) {
console.log(key);
console.log(obj[key]);
}
+3
source to share