How do I pass array as a key in JavaScript object?

Viewed 69

I have an API that expects specialities[] in the request body. The problem is that I don't know how to pass this as key in javascript.

This is what I'm doing:

const data = {
      name: name,
      phone: phone,
      email: registerEmail,
      pmc_number: pmcNumber,
      speciality[]: speciality.split(","),
      city: city 
    }

    const {res} = await axios.post("api-url", data);

But, speciality[] gives syntax error. So, is there any way I can send the data to the API (the API can't be changed. I have to find the solution from the client side). Thanks.

2 Answers
  1. 'specialities': speciality.split(',') describes the property using quotes and not a name, like in JSON.

    However, it is not passing a list/array.

  2. An array is stringified: for example, String([1,2])=='1,2';. So String([])=='', and in a property, which is a string or symbol type, it does not make a difference if you don't try smth like (1.)

You can put quotes around the key.

'specialities[]': speciality.split(","),
Related