Setting a Nested Object with a String Key

February 9, 2010

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

4 Comments to "Setting a Nested Object with a String Key"

  1. JAMES wrote:


    Medicamentspot.com. Canadian Health&Care.No prescription online pharmacy.Special Internet Prices.Best quality drugs. No prescription pills. Buy pills online

    Buy:Retin-A.Synthroid.Actos.Lumigan.Mega Hoodia.Nexium.100% Pure Okinawan Coral Calcium.Arimidex.Accutane.Prevacid.Zovirax.Prednisolone.Human Growth Hormone.Valtrex.Petcam (Metacam) Oral Suspension.Zyban….

  2. HENRY wrote:


    CheapTabletsOnline.Com. Canadian Health&Care.No prescription online pharmacy.Special Internet Prices.Best quality drugs. No prescription pills. Buy pills online

    Buy:Accutane.Petcam (Metacam) Oral Suspension.Synthroid.Actos.Mega Hoodia.Nexium.Lumigan.Prednisolone.Human Growth Hormone.Zovirax.100% Pure Okinawan Coral Calcium.Prevacid.Retin-A.Zyban.Valtrex.Arimidex….

  3. COREY wrote:


    CheapTabletsOnline.com. Canadian Health&Care.No prescription online pharmacy.Best quality drugs.Special Internet Prices. No prescription drugs. Order drugs online

    Buy:Petcam (Metacam) Oral Suspension.Arimidex.Prednisolone.Synthroid.Mega Hoodia.100% Pure Okinawan Coral Calcium.Valtrex.Human Growth Hormone.Lumigan.Zovirax.Retin-A.Prevacid.Zyban.Actos.Nexium.Accutane….

  4. BRIAN wrote:


    NEW FASHION store. Original designers collection at low prices!!! 20 % TO 70 % OFF. END OF SEASON SALE!!!

    BUY FASHION. TOP BRANDS: GUCCI, DOLCE&GABBANA, BURBERRY, DIESEL, ICEBERG, ROBERTO CAVALLI, EMPORIO ARMANI, VERSACE…

 
Powered by Wordpress and MySQL. Theme by openark.org