1

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?

Manuel Bitto
  • 5,073
  • 6
  • 39
  • 47
  • Duplicate of [Javascript: How to set object property given its string name](http://stackoverflow.com/questions/13719593/javascript-how-to-set-object-property-given-its-string-name)...it's basically the same, just the delimiter is different. – Felix Kling Jan 10 '13 at 12:05

2 Answers2

3

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.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

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: {} }}}}
WTK
  • 16,583
  • 6
  • 35
  • 45