Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 705
bob Avatar asked Jul 21 '17 22:07

bob


People also ask

Can we loop an object which is like key-value pairs?

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.

How do I iterate through object keys?

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.


1 Answers

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]);
}
like image 195
Dij Avatar answered Oct 16 '22 12:10

Dij