Search code examples
javascriptjavascript-objects

Convert string array values from URLSearchParams


How does one convert string array values into a Javascript array object?

var querystring = 'lang[]=EN&lang[]=FR&type[]=1&type[]=2';

Into:

{
    lang: ['EN', 'FR'],
    type: ['2']
}

Below my attempt:

let params = new URLSearchParams(decodeURI(querystring));
let entries = params.entries();

let result = {}
for(let entry of entries) { // each 'entry' is a [key, value]
    result[entry[0]] = entry[1];
}
return result;

Which results in:

[{
    "name": "lang[]",
    "value": "EN"
}, {
    "name": "lang[]",
    "value": "FR"
}, {
    "name": "type[]",
    "value": "2"
}]

Solution

  • var querystring = 'lang[]=EN&lang[]=FR&type[]=1&type[]=2';
    let params = new URLSearchParams(decodeURI(querystring));
    let entries = params.entries();
    
    let result = {}
    for(let entry of entries) { // each 'entry' is a [key, value]
        var key = entry[0];
        var val = entry[1];
        if(key in result){
            result[key].push(val);
        }else{
            result[key] = [val];
        }
    }
    console.log(result);