2

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"
}]
5
  • don't understand the expected output, type: [1,2] would make a little sense. Commented Dec 20, 2018 at 2:08
  • @xianshenglu "type" would be an array with IDs in it. Commented Dec 20, 2018 at 2:11
  • Why not use something like npmjs.com/package/query-string or npmjs.com/package/qs Commented Dec 20, 2018 at 2:15
  • @bart, that's not consistent with lang: [EN, FR] Commented Dec 20, 2018 at 2:17
  • @xianshenglu Let me update the above example. Commented Dec 20, 2018 at 2:19

3 Answers 3

3

Simplest version would be to use a library like qs

https://www.npmjs.com/package/qs#parsing-arrays

var withArray = qs.parse('a[]=b&a[]=c');

ressults in

a: ['b', 'c'] 
Sign up to request clarification or add additional context in comments.

2 Comments

I am not running Node.js
You don't have to. Its just Javascript. There's even a CDN cdnjs.com/libraries/qs
3

You should probably test for the [] so your code won't break with entries not ending in []. You can then slice off the [] so your keys don't include it:

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

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

let result = {}
for(let entry of entries) { // each 'entry' is a [key, value]
    let [key, val] = entry
    if (key.endsWith('[]')){         // array 
      key = key.slice(0,-2);         // clean up the key
      (result[key] || (result[key] = [])).push(val)
    } else {
      result[key] = val             // normal parameter
    }
}
console.log(result)

Comments

2

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);

2 Comments

use var key = entry[0].replace("[]", ""); instead
Like @Mark said, this breaks query strings with parameters that are not an array.

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.