Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass array of objects in query string node.js

If I want the Node.js query parser to parse an array, I can send this:

'?or=foo&or=bar' // gets me { or: ['foo', 'bar'] }

If I want an object I can do this:

'?or[foo]=bar' // gets me { or: {foo: 'bar'}}

But how do I get an array of objects? I'd like this output:

{ or: [{foo: 'bar'}, {bar: 'baz'}]}
like image 518
Rob Allsopp Avatar asked Jan 18 '15 02:01

Rob Allsopp


People also ask

Can we pass array in query string Javascript?

We can also pass an array with tuples or a query string. With that done, we now have an instance of the URLSearchParams class. We can get the string version of this by calling toString and append this to our URL.


2 Answers

With the qs module, you can get the object you're looking for if you use this format:

or[0][foo]=bar&or[1][bar]=baz

like image 147
mscdex Avatar answered Oct 11 '22 16:10

mscdex


You can use options allowDots.

const stringParams = qs.stringify(params, {allowDots:true});
// myArray[0].name=MeWhit
qs.parse(stringParams , {allowDots: true});
// [{ name: MeWhit}]
like image 32
Mike Whittom Avatar answered Oct 11 '22 16:10

Mike Whittom