json - Iterating through a javascript object to get key-value pairs - Stack Overflow

Here's my code:obj = {"TIME":123,"DATE":456}console.log(obj.TIME);console

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?

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?

Share Improve this question asked Jul 21, 2017 at 22:10 bobbob 6395 silver badges25 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

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]);
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745623124a4636643.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信