Java script: 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')
How-To add a custom validation method to the jQuery validator plug-in