Reputation: 23
I am trying to set one of the nested subobject properties, but the nested level is dynamic.
how can I dynamically set the nested properties?
It's working only one level properties,i can't set next inner level....
my code:
function deSerialize(qualifiedNameArray, currentIndex, resultJSON, valueToBeInitializedForFinalNode)
{
if (currentIndex == (qualifiedNameArray.length - 1)){
resultJSON [qualifiedNameArray[currentIndex++]] = valueToBeInitializedForFinalNode;
}
else
{
resultJSON [qualifiedNameArray[currentIndex++]] = {};
}
if (currentIndex < qualifiedNameArray.length)
deSerialize( qualifiedNameArray, currentIndex, resultJSON, valueToBeInitializedForFinalNode);
return resultJSON;
}
var results = {"columnname":"person.name.first", "varcharvalue":"david", "objecttype" : "user"};
var valueToBeInitializedForFinalNode = results["varcharvalue"];
var qualifiedNameArray = results["columnname"].split('.');
var resultJSON = {};
deSerialize(qualifiedNameArray, 0, resultJSON, valueToBeInitializedForFinalNode);
Upvotes: 2
Views: 1940
Reputation: 25034
A simple solution might be, not sure if this is what you are looking for:
function makeObj(arry, initValue){
var obj = {}, objRef = obj, idx = 0;
while(idx < arry.length -1){
obj[arry[idx]] = {};
obj = obj[arry[idx]];
idx++;
}
obj[arry[idx]] = initValue;
return objRef;
}
usage:
resultJSON = makeObj( qualifiedNameArray, valueToBeInitializedForFinalNode);
another way is:
function makeObj(objRef, arry, initValue){
var obj = objRef, idx = 0;
while(idx < arry.length -1){
if(!obj[arry[idx]]) obj[arry[idx]] = {};
obj = obj[arry[idx]];
idx++;
}
if(!obj[arry[idx]]) obj[arry[idx]] = initValue;
}
this way, you do not change any values that might have been already present, usage:
makeObj( resultJSON, qualifiedNameArray, valueToBeInitializedForFinalNode);
Upvotes: 2