I want to convert a REST style url into a javascript literal, like this:
from:
var url = "/a/b/c/d";
to:
var obj = {
a:{
b:{
c:{
d:{}
}
}
}
};
How would you do this?
I want to convert a REST style url into a javascript literal, like this:
from:
var url = "/a/b/c/d";
to:
var obj = {
a:{
b:{
c:{
d:{}
}
}
}
};
How would you do this?
You can probably condense it but here's a solution :
var u = '/a/b/c/d';
var t = u.split('/');
var o = {};
for (var i=t.length; i-->1; ) {
var temp = o;
o = {};
o[t[i]] = temp;
}
The result is o
.
My attempt:
var url = '/a/b/c/d';
var fun = function(a) {
var res = {};
res[a[0]] = a.length == 1 ? {} : fun(a.slice(1));
return res;
};
// obj has what you need
var obj = fun(url.split('/').slice(1));
// OTHER EXAMPLE
var t = ['that', 'is', 'so', 'fun'];
console.log(fun(t));
// above returns object: {that: { is: { so: { fun: {} }}}}