Javascript 如何向javascript对象中的一个键添加多个值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33381583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:00:13  来源:igfitidea点击:

how to add many values to one key in javascript object

javascript

提问by jfriend00

I have an object var obj = {key1: "value1", key2: "value2"};I want to add multiple values or array of values to key1 or key2 e.g var obj = {key1: "arrayOfValues", key2: "value2"};is it possible? basically I want to send it to php for process.

我有一个对象,var obj = {key1: "value1", key2: "value2"};我想向 key1 或 key2 添加多个值或值数组,例如 var obj = {key1: "arrayOfValues", key2: "value2"};,这可能吗?基本上我想将它发送到 php 进行处理。

回答by Ali Saberi

You can make objects in two ways.

您可以通过两种方式制作对象。

  1. Dot notation
  2. Bracket notation
  1. 点符号
  2. 括号表示法

Also you can be define values in array with/without initial size. For scenario one you can do the following in worst case scenario:

您也可以在有/没有初始大小的数组中定义值。对于场景一,您可以在最坏的情况下执行以下操作:

var obj = {}
obj.key1 = new Array();
obj.key2 = new Array();
// some codes related to your program
obj.key1.push(value1);
// codes ....
obj.key1.push(value);
// ... same for the rest of values that you want to add to key1 and other key-values

If you want to repeat the above codes in bracket notation, it will be like this

如果你想用括号符号重复上面的代码,它会是这样的

var obj = {}
obj['key1'] = new Array();
obj['key2'] = new Array();
// some codes related to your program
obj['key1'].push(value1);
// codes ....
obj['key1'].push(value);
// ... same for the rest of values that you want to add to key1 and other key-values

With bracket notation, you can use characters e.g 1,3,%, etc. that can't be used with dot notation.

使用括号表示法,您可以使用不能与点表示法一起使用的字符,例如 1,3、% 等。

回答by jfriend00

You can just define an array for the property:

您可以为该属性定义一个数组:

var obj = {key1: ["val1", "val2", "val3"], key2: "value2"};

Or, assign it after the fact:

或者,事后分配:

var obj = {key2: "value2"};
obj.key1 = ["val1", "val2", "val3"];