Friday, April 6, 2012

Get all properties of Object using Javascript.

Goal

Assuming we are working on an a task. On a process we get an object. We don't know what exactly is there in the object or what properties the object is having. The javascript mentioned will print the list of properties of an object.

Solution

<script language="javascript" type="text/javascript">       
    var _jsonObject = {"Property1":1,"Property2":"Simple String","Property3":true};
    alert(_jsonObject);

    var _html = "";
    for (var key in _jsonObject) {
        _html = _html + key + " : " + _jsonObject[key] + "<br />" ;
    }
    document.writeln(_html);
</script>


Output

3 comments:

  1. Open the Feature1 properties. And make the 2 changes shown in the below given image.
    I am unable to see these many peoperties could you please guide me how to open those.

    ReplyDelete
    Replies
    1. @Sam - I think in sending something in comment the information missed out. Can you try agin sending some other way.

      Delete
  2. Another easier way is to use Firebug, got to DOM tab and check your variable. It gives really nice UI for viewing the complete json object (you can check other html objects as well)

    ReplyDelete