Javascript: Set nested object property.

Suppose you have a Javascript object with the following structure:

var obj = {firstname : "Nico",
           lastname:   "Balestra",
           hobbies: [{
                       name: "Clojure",
                       since: "01/03/2012"
                     },
                     {name : "Javascript",
                      since : "01/01/2011"}]
          };
 

and now suppose that your application is such that you need to set one of the attributes of the above object by pointing to that attribute through a Javascript path.
Because you work for a company using Serverside Javascript and you are not allowed to use any library of the like of jQuery, you need to find a way to achieve this yourself.
Therefore, suppose you need to set the date of my Javascript hobby so that it starts the 01/01/2010.
The path referring to that attribute would be obj.hobbies[1].since. So you would like to do something like:

setAttribute(obj, "hobbies[1].since", "01/01/2010");

And this is the setAttribute function

var setAttribute = function(object, path, value){
  var paths = path.split(".");

  var traverse = function(context, pathStack){
    var currPath = pathStack.shift();
    var arr = currPath.match(/\[\d*\]/);

    if (arr != null){
     var arrIdx = parseInt(arr[0].match(/\d+/)[0]);
     var newCurrPath = currPath.replace(/\[\d*\]/, "");
     
     traverse(context[newCurrPath][arrIdx], pathStack);

     }else if ((typeof context[currPath]) == "object"){
	traverse(context[currPath], pathStack);
     }else{
	context[currPath] = value;
    }
  };
	
  traverse(object, paths);
       	
}

I hope this may be of any help.
Nico

One thought on “Javascript: Set nested object property.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>