From an array to object

Hi.


  var str = "/www/admin/video/list/page/2/orderby/1/channel/2/search/myword";
  var chunks = str.split('/');
  var len = chunks.length;
  // I only retrieve /page/2/orderby/1/channel/2/search/myword
  var options = chunks.slice(len-8,len);
  var nlen = options.length;
  var tmp;
  var o = {};
  while(tmp = options.splice(0,2)){
    if(tmp.length === 0){
      break;
    }
    o[tmp[0]] = tmp[1];
  }
  alert(o.page);

Is there a smarter way ?

Bye.

It depends on the form of your input string-
If you always start at the directory ‘/list/’, for instance,
you can make the array starting at the first significant string.

var str= “/www/admin/video/list/page/2/orderby/1/channel/2/search/myword”

var o= {},chunks= str.substring(str.indexOf('/list/')+5),
i= 0, opts= chunks.match(/([^\\/]+)/g), L= opts.length-1;
while(i<L){
	o[opts[i++]]= opts[i++];
}
//test
var ostring= 'o={\
\	';
for(var p in o){
	ostring+= p+':'+o[p]+',\
\	';
}
alert(ostring+'\
}');

/* returned value: (String)
o={
page:2,
orderby:1,
channel:2,
search:myword,
}

Cool :slight_smile:
Thanks a lot.
Bye

I mixed up


function pathToObject(path,offset){
  var chunks = path.split('/');
  var lenChunks = chunks.length;
  var opts = chunks.slice(lenChunks-offset,lenChunks);
  var o = {}, i= 0, len = opts.length-1;
  while(i<len){
    o[opts[i++]]= opts[i++];
  }
  return o;
}
var o = pathToObject("/www/admin/video/list/page/2/orderby/1/channel/2/search/myword",8);
var ostring= 'o={\
\	';
for(var p in o){
  ostring+= p+':'+o[p]+',\
\	';
}
alert(ostring+'\
}');

(: