Reputation: 7563
There is the request: /test?strategy[]=12&strategy[]=23
In PHP we may receive array with this code:
$_GET['strategy']
It will be array even if it has 1 param.
In JS we can use this code:
var query = url.parse(request.url, true).query;
var strategy = query['strategy[]'] || [];
But if there will be 1 param strategy
( /test?strategy[]=12
), it will not be an array.
I think it's a dirty solution to check count of elements and convert strategy
to [strategy ]
if it equals to 1.
How can I get an array from query in Node.js?
Upvotes: 3
Views: 2288
Reputation: 41440
Node itself doesn't parse those types of arrays - nor it does with what PHP calls "associative arrays", or JSON objects (parse a[key]=val
to { a: { key: 'val' } }
).
For such problem, you should use the package qs to solve:
var qs = require("qs");
qs.parse('user[name][first]=Tobi&user[email][email protected]');
// gives you { user: { name: { first: 'Tobi' }, email: '[email protected]' } }
qs.parse("user[]=admin&user[]=chuckNorris");
qs.parse("user=admin&user=chuckNorris");
// both give you { user: [ 'admin', 'chuckNorris' ] }
// The inverse way is also possible:
qs.stringify({ user: { name: 'Tobi', email: '[email protected]' }})
// gives you user[name]=Tobi&user[email]=tobi%40learnboost.com
Upvotes: 3