Friday, August 22, 2008

JavaScript: access properties of a complex JSON object

Lately I needed to dynamically access the value of a nested property in a complex JSON object in a JQuery plug-in I wrote. Since to my knowledge this is not possible directly I wrote a little function in Java Script.

var findValue = function(item, name) {
    var token = /\w+/g;
    var results = name.match(token);
    var temp = item;
    for (var i = 0; i < results.length; i++)
        temp = temp[results[i]];
    return temp;
}  

First I use a regular expression to find all property names which are separated (witch are separated by a dot in my case). Then I loop over the matches and move forward in the object tree.

If I now have an object as follows

var item = {
  Id: 1,
  Name: { FirstName: "Gabriel", LastName: "Schenker" },
  ...
}

I can access the value of the LastName property with this function call

findValue(item, 'Name.FirstName')

Enjoy!

3 comments:

Radha Krishna said...

thanks, that saved me a lot of time, is there a way to find out all of the properties in a JSON object? and where would I find information on javascript API to understand the JSON object (I am using mostly prototype and rarely JQuery); there is decent Java API but no good javascript API to understand/read the JSON object!

Your idea helped me in updating specific properties directly from JSON objects key - value pairs!

Radha Krishna said...
This comment has been removed by the author.
Radha Krishna said...
This comment has been removed by the author.