Ville Miekk-oja
Ville Miekk-oja

Reputation: 20935

Javascript object literal - possible to add duplicate keys?

In javascript, is is possible to add duplicate keys in object literal? If it is, then how could one achieve it after the object has been first created.

For example:

exampleObject['key1'] = something;
exampleObject['key1'] = something else;

How can I add the second key1 without overwriting the first key1?

Upvotes: 13

Views: 34635

Answers (3)

shweta ghanate
shweta ghanate

Reputation: 279

In javascript having keys with same name will override the previous one and it will take the latest keys valuepair defined by the user.

Eg:

var fruits = { "Mango": "1", "Apple":"2", "Mango" : "3" }

above code will evaluate to

var fruits = { "Mango" : "3" , "Apple":"2", }

Upvotes: 3

Nicholas Robinson
Nicholas Robinson

Reputation: 1419

No it is not possible. It is the same as:

exampleObject.key1 = something;
exampleObject.key1 = something else; // over writes the old value

I think the best thing here would be to use an array:

var obj = {
  key1: []
};

obj.key1.push("something"); // useing the key directly
obj['key1'].push("something else"); // using the key reference

console.log(obj);

// ======= OR ===========

var objArr = [];

objArr.push({
  key1: 'something'
});
objArr.push({
  key1: 'something else'
});

console.log(objArr);

Upvotes: 15

hsz
hsz

Reputation: 152226

You cannot duplicate keys. You can get the value under the key1 key and append the value manually:

exampleObject['key1'] = something;
exampleObject['key1'] = exampleObject['key1'] + something else;

Another approach is the usage of an array:

exampleObject['key1'] = [];
exampleObject['key1'].push(something);         
exampleObject['key1'].push(something else);

Upvotes: 6

Related Questions