3

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?

1 Answer 1

3

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
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.