Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: arrays in query

Tags:

node.js

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?

like image 347
Dmitry Avatar asked Dec 07 '25 09:12

Dmitry


1 Answers

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
like image 161
gustavohenke Avatar answered Dec 10 '25 04:12

gustavohenke