Javascript object literal – possible to add duplicate keys?

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

Leave a Comment