3

What I ultimately want to have is:

import qs as 'qs'

qs.stringify({
      country: 'us',
      currency: 'USD',
      'kw[]': 'apple',
      'kw[]': 'banana',
      'kw[]': 'pear',
    })

But currently, I have:

const keywords = ['apple', 'banana', 'pear']

How can I convert that to the kw[] syntax?

3
  • I would use reduce personally. You can reduce the array to an object. Commented Sep 7, 2020 at 0:05
  • Can you give an example? Commented Sep 7, 2020 at 0:09
  • Not right now no. The key is to return an object and not an array from the reducer. Commented Sep 7, 2020 at 0:26

1 Answer 1

1
import qs from 'qs';
const keywords = ['apple', 'banana', 'pear'];
const queryObject = { country: 'us', currency: 'USD', kw: keywords };
const queryString = qs.stringify(queryObject);
console.log(queryString);

The above will output:

country=us&currency=USD&kw%5B0%5D=apple&kw%5B1%5D=banana&kw%5B2%5D=pear

Decoded, it looks like this:

country=us&currency=USD&kw[0]=apple&kw[1]=banana&kw[2]=pear
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.