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?
An object can have two same keys or two same values.
It is not allowed to have duplicated keys in a HashMap. You have to use another structure.
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.
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);
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);
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", }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With