SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    From an array to object

    Hi.
    Code JavaScript:
      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.

  2. #2
    SitePoint Guru
    Join Date
    Apr 2006
    Posts
    802
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    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"
    Code:
    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++];
    }


    Code:
    //test
    var ostring= 'o={\n\t';
    for(var p in o){
    	ostring+= p+':'+o[p]+',\n\t';
    }
    alert(ostring+'\n}');
    /* returned value: (String)
    o={
    page:2,
    orderby:1,
    channel:2,
    search:myword,
    }
    Last edited by mrhoo; May 1, 2010 at 08:27. Reason: format

  3. #3
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Cool
    Thanks a lot.
    Bye

  4. #4
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I mixed up
    Code JavaScript:
    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={\n\t';
    for(var p in o){
      ostring+= p+':'+o[p]+',\n\t';
    }
    alert(ostring+'\n}');


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •