Enumerating properties of an Object in Javascript

<html>
  <body>
    <pre>

<script>
      var myApp = {};
      myApp.stooge = {
        first_name: 'Jerome',
        status: 'novice'
      };

      function enumerate(obj) {
        var f;
        for (f in obj) {
          if (typeof f !== 'function' &&  // I want properties only.
              obj.hasOwnProperty(f)) {    // Don't follow prototype link.
            document.writeln(f + ': ' + obj[f]);
          }
        }
      }

      enumerate(myApp);
      enumerate(myApp.stooge);
</script>

    </pre>
  </body>
</html>

output:

stooge: [object Object]
first_name: Jerome
status: novice

Based on the code of Chap 3. Objects in Javascript: The Good Parts.

Similar Posts:

Post a Comment

Your email is never published nor shared.