Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object literal - possible to add duplicate keys?

Tags:

javascript

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?

like image 248
Ville Miekk-oja Avatar asked Aug 05 '16 13:08

Ville Miekk-oja


People also ask

Can an object key have multiple values JavaScript?

An object can have two same keys or two same values.

Can HashMap have duplicate keys in JavaScript?

It is not allowed to have duplicated keys in a HashMap. You have to use another structure.

Can set have duplicate keys?

Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.


3 Answers

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);
like image 101
Nicholas Robinson Avatar answered Oct 27 '22 09:10

Nicholas Robinson


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);
like image 41
hsz Avatar answered Oct 27 '22 11:10

hsz


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", }
like image 20
shweta ghanate Avatar answered Oct 27 '22 11:10

shweta ghanate