Zain
Zain

Reputation: 55

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

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.

Upvotes: 1

Views: 670

Answers (2)

user19987349
user19987349

Reputation: 11

  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, does it make much of a a difference?

Upvotes: 1

Unmitigated
Unmitigated

Reputation: 89374

You can put quotes around the key.

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

Upvotes: 1

Related Questions