简体   繁体   中英

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.

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

However, it is not passing a list/array.

  1. 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.)

Have a blessed day!

You can put quotes around the key.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM