Snippet to enumerate JavaScript object properties

Published:

Updated:

In writing some JavaScript code today, I had to write a function that was being called by some other JavaScript function, and I had no idea how many argument (parameters) were being sent by that other function, or what the contents of those argument would be. 

So, I figured out a nice way to determine what was being sent to my function.

First, determining the number of arguments being sent was pretty easy.  In every function, JavaScript automatically creates an array called arguments[].  So to find out how many arguments are being passed to my function, I created the following code:

function myFunction() {
  alert
(arguments.length);
};

Then, when I opened the web page and the JavaScript function was called, I saw a "2" displayed in an alert box, so 2 arguments were being passed.  That part was easy!

Next, I changed my function to display what type of arguments were being passed:

function myFunction() {
  alert(typeof arguments[0]);
  alert(typeof arguments[1]);
};

Then when the function executed I saw 2 alert boxes, each with the word "object".  So I knew I was being passed 2 objects as arguments.

The last step was to examine the 2 objects to see what was inside them.  To do that I came up with a way to enumerate the properties of each object.

In JavaScript objects are really nothing more than arrays that are stored in something called "JSON" (JavaScript Object Notation).  JSON represents objects as arrays of name/value pairs.  The name part is a string value and the value part is any valid JavaScript type, such as string, number, or function.

So enumerating the object properties was just a matter of using two for loops to read all the elements of the array.  The function became:

function myFunction(arg1, arg2) {
   var property, properties="";

   for(property in arg1){
      properties += (property + ": " + arg1[property] + "\n");
   }

   alert(properties);
  properties="";

   for(property in arg2){
      properties += (property + ": " + arg2[property] + "\n");
   }

   alert(properties);
};

Then when the function executed I saw two alert boxes, the first one showing full contents of the first argument, and the second alert box showing the contents of the second argument.

Now that I know the contents of the arguments, I can go on and finish my JavaScript function!

This is a nice little snippet to keep in reserve in case something like this happens again.

Entry #160

Comments

This Blog entry currently has no comments.

Post a Comment

Please Log In

To use this feature you must be logged into your Lottery Post account.

Not a member yet?

If you don't yet have a Lottery Post account, it's simple and free to create one! Just tap the Register button and after a quick process you'll be part of our lottery community.

Register