Click here to Skip to main content
Licence CPOL
First Posted 6 Jun 2011
Views 3,953
Bookmarked 0 times

JavaScript Looping Through Object Properties

By | 6 Jun 2011 | Technical Blog
Looping through JSON object properties in JavaScript.
A Technical Blog article. View original blog here.[^]

My previous post contained a small piece of code explaining how to loop through object properties with the Reflection namespace in C#.

In this post, I'd like to explain how to loop through a JavaScript object.

Let's create an object in JavaScript:

var myObject = {
    Name: "Elad",
    LastName: "Shalom",
    Age: 26,
    Kids: ["Daniel"]
};

This object contains four properties:

  1. Name (string)
  2. LastName (string)
  3. Age (int)
  4. Kids (array)

Now for the loop part:

function LoopThroughProperties(obj)
{
    for (var propName in obj) 
    {
        alert(propName + ": " + obj[propName]); 
    }
}

The function will receive an object and loop through all of its properties.

I'd like to explain a bit about the for syntax I used. Those of you who write in C#/ VB/ Java will find it very similar to the foreach loop in JavaScript.

Since an object in JavaScript is a form of array, I can easily call every one of its properties the same way (almost) I'd call them when looping through an array. This type of foreach loop in JavaScript is also very useful when going through a hash table. Since we won't know the numbers the hash contains, we can simply loop through it.

Thanks.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

DevAffair

Team Leader
Sports Betting Tech
Israel Israel

Member

Follow on Twitter Follow on Twitter


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
General[My vote of 2] JavaScript Looping Through Object Properties PinmemberAfter20502:27 6 Jun '11  
GeneralRe: [My vote of 2] JavaScript Looping Through Object Properties PinmemberElad10103:15 6 Jun '11  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 6 Jun 2011
Article Copyright 2011 by DevAffair
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid