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')
Post Footer automatically generated by Add Post Footer Plugin for wordpress.
About Gabriel Schenker
Gabriel N. Schenker started his career as a physicist. Following his passion and interest in stars and the universe he chose to write his Ph.D. thesis in astrophysics. Soon after this he dedicated all his time to his second passion, writing and architecting software. Gabriel has since been working for over 12 years as an independent consultant, trainer, and mentor mainly on the .NET platform. He is currently working as chief software architect in a mid-size US company based in Austin TX providing software and services to the pharmaceutical industry as well as to many well-known hospitals and universities throughout the US and in many other countries around the world. Gabriel is passionate about software development and tries to make the life of developers easier by providing guidelines and frameworks to reduce friction in the software development process.
Gabriel is married and father of four children and during his spare time likes hiking in the mountains, cooking and reading.
This entry was posted in
jQuery,
plugins. Bookmark the
permalink. Follow any comments here with the
RSS feed for this post.