11

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.

2
  • obj.key1 = "arrayOfValues". Is this what you mean? I’m failing to see where exactly you’re struggling. If you know the JS array syntax, this should be trivial. Commented Oct 28, 2015 at 1:53
  • yes may be I am not sure Commented Oct 28, 2015 at 1:59

3 Answers 3

20

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"];
Sign up to request clarification or add additional context in comments.

Comments

17

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.