简体   繁体   中英

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!

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

The third try is promising, but wrong implemented. To get the desired output, you can use

function objectString(obj) {
    var keys = Object.keys(obj);
    return keys.map(v => v + ": " + obj[v]).join("\n");
}

console.log(objectString(obTest));

Use Object.keys() to get list of keys of an object. Then iterate to get their values.

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

Object.keys(obTest).forEach(function(key){        
    if (obTest.hasOwnProperty(key)){
        console.log(key + ":" + obTest[key]); 
    }
});

Just use the example from the MDN Docs

for (var property in obTest) {
    if( obTest.hasOwnProperty( property ) ) {
       console.log(property + ": " + obTest[property])
    }
}

One of the problems is that you are missing a " behind the value of your "Website"-property.

http://codepen.io/anon/pen/ozKENQ

Object.keys(your_object) is your friend, it converts an object to an array. Check out the documentation here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM