最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin6PV0评论

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

Post a comment

comment list (0)

  1. No comments so far