Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
53
rated 0 times [  58] [ 5]  / answers: 1 / hits: 27098  / 8 Years ago, fri, august 5, 2016, 12:00:00

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?


More From » javascript

 Answers
12

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




[#61135] Wednesday, August 3, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cameron

Total Points: 591
Total Questions: 112
Total Answers: 88

Location: Botswana
Member since Sat, Jan 7, 2023
1 Year ago
;