1

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
  • 1
    The key isn't supposed to be a type, it should be an identifier. The type can be whatever you assign it. .split() already creates an array, so just remove the [] from the key name. If the api requires you to include the [] in the key name then just quote the key so it's a string. Commented Sep 13, 2022 at 15:25
  • Put quotes around object keys that contain special characters. "speciality[]": value Commented Sep 13, 2022 at 15:28

2 Answers 2

1

You can put quotes around the key.

'specialities[]': speciality.split(","),
Sign up to request clarification or add additional context in comments.

2 Comments

close for clarity, it looks like the OP is confusing type annotations with property names.
Though if for some reason the API requires specialties[] as a key, then this answer seems appropriate. If the OP has any control over the API I would highly recommend removing [] from the key though.
1
  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?

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.