Enumerating properties of an Object in Javascript

Tags:

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

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *