13

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?

6
  • Can't. It'll update the value. Commented Aug 5, 2016 at 13:11
  • How would you expect to use that? Commented Aug 5, 2016 at 13:12
  • @Ville: How would you want to access the value and know which version it is? Commented Aug 5, 2016 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. Commented Aug 8, 2016 at 7:16
  • Does this answer your question? JS associative object with duplicate names Commented Sep 19, 2020 at 5:57

3 Answers 3

15

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);

Sign up to request clarification or add additional context in comments.

Comments

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);

1 Comment

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.
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", }

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.