Skip to content Skip to sidebar Skip to footer

Read And Loop Through An Object With Non-unique Key Value Pairs

I have an object which contains some key/value pairs. When there is a key/value pair that shares the same key as another key/value pair, the first one is not recognised when I cons

Solution 1:

An object can not have duplicate keys.

So the reason that you can't read the duplicate keys from the object, is that they were never added as two items in the object in the first place. One of the items will simply overwrite the other.


Solution 2:

Could you change the structure of the JSON if needed? JSON objects cannot have duplicate keys. Think of it as a hashmap or dictionary. Depending on the language and JSON parser you may also get an exception (not in Javascript though)

In your example above either change it so that you have unique keys or change ti to an array of values like:

var test = {
"same" : ['Value1', 'Value2']
"different" : 'Value3'
};
console.log(test);

Solution 3:

A key is a unique value that uniquely identifies the element within the array/object. So, the answer is no, you can't have two elements with the same key value.


Post a Comment for "Read And Loop Through An Object With Non-unique Key Value Pairs"