10

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?

Ville Miekk-oja
  • 18,749
  • 32
  • 70
  • 106
  • Can't. It'll update the value. – Tushar Aug 05 '16 at 13:11
  • How would you expect to use that? – David H. Aug 05 '16 at 13:12
  • @Ville: How would you want to access the value and know which version it is? – lxg Aug 05 '16 at 13:12
  • I'm about to generate an xml from that object. And that xml contains elements that have exactly the same name (Though they contain atttributes with different values). Mm.. maybe I need to generate the xml first without those duplicates, and then try to add those duplicate elements later in the process. – Ville Miekk-oja Aug 08 '16 at 07:16
  • Does this answer your question? [JS associative object with duplicate names](https://stackoverflow.com/questions/3996135/js-associative-object-with-duplicate-names) – Ganesh Chowdhary Sadanala Sep 19 '20 at 05:57
  • What you have there is not an object literal. As an object literal, your example would look like: `{ key1: something, key1: something else }` – Stewart Sep 21 '20 at 10:38

3 Answers3

11

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);
Nicholas Robinson
  • 1,359
  • 1
  • 9
  • 20
6

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);
hsz
  • 148,279
  • 62
  • 259
  • 315
  • I think it's because you cannot just do arithmetic operations with any variable. The user did not specify what type of variable "something" is. However, the array implementation would work. – David H. Aug 05 '16 at 13:37
3

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", }
Dorian Turba
  • 3,260
  • 3
  • 23
  • 67
shweta ghanate
  • 281
  • 2
  • 4