0

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.

8

1 Answer 1

0

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.