Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Is there a way to get the values always inside arrays, even for single values? #228

Open
cbdeveloper opened this issue Dec 19, 2019 · 4 comments

Comments

@cbdeveloper
Copy link

cbdeveloper commented Dec 19, 2019

Is there a way to make sure that all parsed values will be inside arrays, even if they're single values?

I mean

Search string: ?foo1=bar1&foo2=bar1,bar2

queryString.parse(props.location.search,{arrayFormat: 'comma'});

I'm getting:

{
  foo1: bar1,
  foo2: [ bar1,bar2 ]
}

And I would like to always get:

{
  foo1: [ bar1 ],                    // Single value inside array always
  foo2: [ bar1,bar2 ]
}

Is it possible?

This would help me to verify if a filter is present on the string. I would check the indexOf for the array, instead of checking if it's an array first, and handling it differently if it's a single values. In my case, all of my filters allow multiple choices, hence they can always be inside arrays.

Thanks

@sindresorhus
Copy link
Owner

There's currently no way to do this. We need a way to make it unambiguous. Maybe introduce some kind of schema functionality, where you can define the type of some or all keys.

@sindresorhus
Copy link
Owner

Or in your case, you could use a less ambiguous format like {arrayFormat: 'bracket'}.

@alantanlc
Copy link

One way to work around this for now could be like this. @cbdeveloper

values = queryString.parse(props.location.search,{arrayFormat: 'comma'})
if(!Array.isArray(values.foo1) {
  values.foo1 = [values.foo1] 
}

or

values = queryString.parse(props.location.search,{arrayFormat: 'comma'})
values.foo1 = !Array.isArray(values.foo1) ? [values.foo1] : values.foo1

@DV8FromTheWorld
Copy link
Contributor

If you're still wanting to use the condensed format of comma while achieving support for empty arrays, an explicit format like the proposal for arrayFormat: bracket-separator might be able to achieve that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants