ok, so I have an object like:
var myobject = {
"field_1": "lorem ipsum",
"field_2": 1,
"field_2": 2,
"field_2": 6
};
as you see there are duplicate names in the object, but with different values. If i go through it like (using jQuery):
$.each(myobject, function(key, value)
{
console.log(key);
console.log(myobject[key]);
console.log(myobject[value]);
}
key - returns the correct key
myobject[key] - returns the name for that key
myobject[value] - returns the last elements', with that name, value
meaning for field_2 it will return 6, though it'll print it 3 times, as it repeats 3 times in the object.
My question is how to obtain the correct value for that duplicate named fields and not just the last one's
Thank you
You can't do this. The array key must be unique.
If you've got Firefox/Firebug installed (or similar in another browser), you can try it by entering this into the Firebug console:
Firebug will respond with:
in other words, it works, but each subsequent value specified for field_2 overwrites the previous one; you can only have one value for it at a time.
The closest you can get to what you want is to make field_2 an array in itself, something like this:
If you do
console.log
now, you'll get this:Hope that helps.
Test
OUTPUT
That is not an array that is an object. You'd be better creating a property of the object that is an array and store the different values in there.
then just loop through that property of the array.
It is not possible.
The resulting object does only contain 2 elements, the first and second field_2 elements are lost on creation.
The only way to get around it would be to either change the fields to unique identifiers, or something like:
You're overwriting the same value several times.
What you want is probably something like:
Which could be written in a manner similar to what you currently have:
Note that I made
field_1
an array as well, which - for consistency - I thought you might want.