简体   繁体   English

如何在 JavaScript object 中将数组作为键传递?

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

I have an API that expects specialities[] in the request body.我有一个 API 期望在请求正文中包含 specialities specialities[] The problem is that I don't know how to pass this as key in javascript.问题是我不知道如何将其作为 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.但是, speciality[]给出了语法错误。 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).那么,有什么办法可以将数据发送到 API(API 无法更改。我必须从客户端找到解决方案)。 Thanks.谢谢。

  1. 'specialities': speciality.split(',') describes the property using quotes and not a name, like in JSON. 'specialities': speciality.split(',')使用引号而不是名称来描述属性,例如 JSON。

However, it is not passing a list/array.但是,它没有传递列表/数组。

  1. An array is stringified: for example, String([1,2])=='1,2';数组是字符串化的:例如, 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.)所以String([])=='' ,在一个字符串或符号类型的属性中,如果你不尝试像 (1.)

Have a blessed day!有一个幸福的一天!

You can put quotes around the key.您可以在键周围加上引号。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Javascript 中将数组值作为 object 键传递 - How to pass array value as object key in Javascript Javascript:如何在我的阵列中使用特定键删除 object? - Javascript: How do I remove an object with a specific key in my array? JavaScript:如何添加自定义 class object 作为数组的键 - JavaScript: How do I add a custom class object as a key of an array 我如何使用javascript中具有相同键的对象从对象中创建具有对象数组的对象数组 - how do I create an array of objects with array in the object from an object with the same key in javascript 如何在javascript中将值传递给对象? - How do I pass a value to an object in javascript? JavaScript-如何从字符串名称调用函数并传递数组对象? - JavaScript - How do I call a function from a string name and pass an array object? 如何将变量作为键传递给javascript unshift / push? - how do I pass a variable as key into a javascript unshift/push? 如何在 Javascript 中传递一个数组和一个 object 作为参数? - How do you pass an array and an object as an argument in Javascript? 如何检查数组 Javascript 中是否存在 object 数组键 - How I can check if a object array key exists in Array Javascript 如何在JavaScript中将此对象转换为数组? - How do I convert this object to an array in JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM