Feb
09
2010

Setting a Nested Object with a String Key

In one of the projects that I’m working on I had to setup a property of an object in a general way. In order to do so, i wrote the following function:


function setValue(key,value,obj){
    obj[key.toString()] = value;
}

so calling the functuion like so


var obj = { a:1,b:2,c:3 };
setValue( "a" , 2 , obj );

will result obj.a to be 2.
But while developing this project my client had to make some changes and the object that i  expected in the function is now a nested object like so:


var obj = { a:1, nested: { b1: 2, b3: 3} , c: 4};

Clearly using my original setValue method wouldn’t work


setValue("nested.b1", 2, obj); //Error!

In order to solve this i used a little trick with recursion:


function setValue(key,value,obj){
    var keys = key.split(".");
    if( keys.length == 1 ){
        obj[key.toString()] = value;
    }
    else{
        var innerObj = obj[keys[0]];
        keys.shift();
        var updatedKey = keys.join(".");
        setValue( updatedKey, value, innerObj);
    }
}

The function work like so: I always try to split the string in an aaray of strings using the split method. so if i get the following string “a.b.c” i will get an array of strings like so: ["a","b","c"]. The split method will have no affect if the string has no dots in it.

I then check the length of the string array. If it has only one element then i assume that there is no nested assignments and i use the original code i used. But if there is, i get the new nested object using the first element of the array and then i remove this element and create back the string using the join method, and call the function in recursion with the nested object.

Now i can use this function in the following way:


var obj = { a: { b: { c: 0 } } };
setValue("a.b.c" , 1 , obj ); // obj.a.b.c = 1

Now my client is happy and i got another cool post.

Bookmark and Share
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • E-mail this story to a friend!
  • FriendFeed
  • LinkedIn
  • StumbleUpon
  • Twitter

tags: , , , , ,
posted in Blog by Amir Harel

Follow comments via the RSS Feed | Leave a comment | Trackback URL

blog comments powered by Disqus
 
Powered by Wordpress and MySQL. Theme by openark.org