I have the following input:
var input = {
"usa.ca.los": 12345,
"usa.ca.sfo": 12346,
"usa.ws.sea": 22333,
"others.a.b.c.d.e": 33333
}
and I want to turn it into:
var output = {
"usa": {
"ca": {
"los": 12345,
"sfo": 12346,
},
"ws": {
"sea": 22333
}
}
"others":{"a":{"b":{"c":{"d":{"e":33333}}}}}
}
I know I can use a recursive function and construct the output but seems like too much work.
Since my program in in Node.js, is there a simpler way to do it using underscore.js? or some other existing functions can make me do the conversion properly?
I don't think theres an inbuilt function in underscore to do that, but its a fairly simple matter to write one yourself:
var input = {
"usa.ca.los": 12345,
"usa.ca.sfo": 12346,
"usa.ws.sea": 22333,
"others.a.b.c.d.e": 33333
}
function parse(input){
var output = {};
for(var key in input){
setByString(output, input[key], key);
}
return output;
}
function setByString(obj, value, key){
var split = key.split('.');
while(split.length){
key = split.shift();
if(split.length){
if(!obj.hasOwnProperty(key)){
obj[key] = {};
}
obj = obj[key];
} else {
obj[key] = value;
}
}
}
console.log(parse(input));