最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论