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.









JAMES wrote:
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….
Link | July 21st, 2010 at 3:16 pm
HENRY wrote:
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….
Link | September 5th, 2010 at 12:24 pm
COREY wrote:
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….
Link | September 6th, 2010 at 8:44 am
BRIAN wrote:
…
BUY FASHION. TOP BRANDS: GUCCI, DOLCE&GABBANA, BURBERRY, DIESEL, ICEBERG, ROBERTO CAVALLI, EMPORIO ARMANI, VERSACE…
Link | November 10th, 2010 at 8:38 pm