how to add many values to one key in javascript ob

2020-06-16 03:17发布

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.

标签: javascript
2条回答
We Are One
2楼-- · 2020-06-16 03:44

You can make objects in two ways.

  1. Dot notation
  2. Bracket notation

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.

查看更多
Explosion°爆炸
3楼-- · 2020-06-16 03:55

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"];
查看更多
登录 后发表回答