简体   繁体   中英

How to convert array parameters from url into an object in javascript?

After decode GET parameters:

var query = decodeURIComponent(document.location.search)

I get:

a[0]=data&a[1][one]=data&a[1][two]=data&b=data

I need to convert it into an object like this:

myObject = {
    a : {
          0 : data,
          1 : {
              one : data,
              two: data
          }
    },
    b : data
}

I don't know how to do it. I am blank.

EDIT. This problem is quite different from possible duplicates. Here I have an multidimensional array. I could split that very easily into this:

myObject = {
   "a[0]" : data,
   "a[1][one]" : data,
   //etc
}

but I don't need that.

I figured out a temporary solution, surely an awful and not proper one. Till I have a better one, I will use this. I think It may be useful to someone.

Next, I share a version of a till two level dimensional array. But it can be adapted to a deeper one:

function getParams() {
    var query = decodeURIComponent(document.location.search.substring(1));
    var params = {},
        tokens,
        r = /[?&]?([^=]+)=([^&]*)/g;

    var key, value, match = [],
        re = /\[([^\]]*)\]/g;

    while (tokens = r.exec(query)) {
        value = tokens[2];
        key = tokens[1].split('[');
        key = key[0];
        match = [];
        while ( (  res = re.exec(tokens[1]) ) != null ){
           match.push(res[1])
        }

        if (match) {
            switch (match.length) {
                case 1 :
                    params[key] = params[key] || {};
                    params[key][match[0]] = value;
                    break;
                case 2 :
                    params[key] = params[key] || {};
                    params[key][match[0]] = params[key][match[0]] || {};
                    params[key][match[0]][match[1]] = value;
                    break;
            }
        } else {
            params[key] = value;
        }
    }

    return params;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM