host_255 host_255 - 1 month ago 5
Javascript Question

Cannot iterate through JavaScript object

As a matter of exercise, I am trying to learn how to print the key and value of a JS object. I am having a hard time.

The following is a basic object I wrote and want to just print out the

key : value


var obTest = {
name: "John",
WeddingDate: "10/18/2008",
NumberKids: "2",
Website: "www.samplewebsite.com
};


/* VERSION 1
for (var key in obTest) {
// skip loop if the property is from prototype
if (!obTest.hasOwnProperty(key)) continue;

var obKey = obTest[key];
for (var obProp in obKey) {
// skip loop if the obProperty is from prototype
if(!obKey.hasOwnProperty(obProp)) continue;

// your code
alert(obProp + " : " + obKey[obProp]);
}
};
// note: this prints each character as a key:value
*/

/* VERSION 2
for (var key in obTest) {
if (obTest.hasOwnProperty(key)) {
var obKey = obTest[key];
for (var prop in obKey) {
if (obKey.hasOwnProperty(prop)) {
console.log(prop + " : " + obKey[prop]);
}
}
}
};
// note: this prints each character as a key:value
*/


// VERSION 3
Object.keys(obTest.forEach(function(key) {
console.log(key, obTest[key]);
}));
// note: this gives me a breakpoint and can't figure out why it does not work


As noted, VERSION 1 and VERSION 2 print the same output as follows:

0 : J
1 : o
2 : h
3 : n
0 : 1
1 : 0
2 : /
3 : 1
4 : 8
5 : /
6 : 2
7 : 0
8 : 0
9 : 8
0 : 2
0 : w
1 : w
2 : w
3 : .
4 : s
5 : a
6 : m
7 : p
8 : l
9 : e
10 : w
11 : e
12 : b
13 : s
14 : i
15 : t
16 : e
17 : .
18 : c
19 : o
20 : m


I get a breakpoint using Visual Studio Code for VERSION 3.

Please help me make an output like this:

name : John
WeddingDate : 10/18/2008
NumberKids : 2
Website : www.samplewebsite.com


I do not want to have numerical keys, especially ones that repeat themselves. Other articles I read don't seem to make any sense. Python seems pretty straightforward about iterating and printing object keys and values.

Thank you!

Answer

You're using two nested loops, when one would be enough:

for (var key in obTest) {
  // skip loop if the property is from prototype
  if (!obTest.hasOwnProperty(key)) continue;
  //find the object corresponding to the current key
  var obKey = obTest[key];
  //output the key and the corresponding object  
  alert(key + " : " + obKey);
};

With your second loop, you enumerate all the pairs "keys : values" inside each value of your object. For a string "John", the pairs key:values are (0:"J", 1:"o", 2:"h", 3:"n")

For the version 3, you got the parenthesis wrong:

Object.keys(obTest) //close parenthesis of keys here
      .forEach(function(key) {
         console.log(key, obTest[key]);  
       });  //close only forEach here