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.
3 Answers
You can make objects in two ways.
- Dot notation
- 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
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.
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.