简体   繁体   中英

how to add many values to one key in javascript object

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

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 eg 1,3,%, etc. that can't be used with dot notation.

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"];

I came across same scenario and after scanning through many resources I found very elegant solution. Using Bracket Notation one can add multiple values to same key

let obj = {}
const demo = (str, objToAdd) => {
if(!obj[str]){
obj[str] = {}
}
const key = Object.keys(objToAdd)[0]
obj[str][key] = Object.values(objToAdd)[0]
}

Here important line is obj[str][key] = Object.values(objToAdd)[0] . This line will help you create object inside same key. obj[str][key] will create object inside object. to add values call function as below

demo('first', {content: 'content1' } )
demo('first', {content2: 'content3' } )

obj

first: {content: "content1", content2: "content3"}

Hopefully this will help someone.

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