Skip to content Skip to sidebar Skip to footer

Js Associative Object With Duplicate Names

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

Solution 1:

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.

var myarray = {
   "field_1": "lorem ipsum",
   "field_array": []
};

myarray.field_array.push(value);

then just loop through that property of the array.

Solution 2:

  1. Your code has invalid syntax.
  2. There are no assocative arrays in Javascript
  3. The thing you defined is an Object
  4. If you give value to a property 3 times, sure it will contain the last value

Test

var obj = {
   "field_1": "lorem ipsum",
   "field_2": 1,
   "field_2": 2,
   "field_2": 6
};

for ( var i in obj ) {
  console.log(i + " = " + obj[i]);
}

OUTPUT

field_1 = lorem ipsum
field_2 = 6

Solution 3:

Associative arrays do not exist in Javascript - what you have created is an Object using the JSON format.

I suspect that something like this will give you more what you are seeking, though I suggest questioning exactly what it is that you are trying to achieve..

The following code will allow you to access multiple instances of duplicated 'keys', but is

var myDataset = [
   { "field_1": "lorem ipsum" },
   { "field_2": 1 },
   { "field_2": 2 },
   { "field_2": 6 }
];


$.each(myDataset, function(valuePairIndex, value)
{
    $.each(myDataset[valuePairIndex], function(key, value1)
    {
       var valuePair = myDataset[valuePairIndex];
       console.log(valuePairIndex);
       console.log(key + ' = ' + valuePair[key]);

//       console.log('key = ' + key);//       console.log('valuePair[key] = ' + valuePair[key]);
    });
});

Solution 4:

The keys must be unique.

Solution 5:

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:

var myarray = {
   "field_1": "lorem ipsum",
   "field_2": 1,
   "field_2": 2,
   "field_2": 6
};
console.dir(myarray);

Firebug will respond with:

field_1      "lorum ipsum"
field_2      6

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:

var myarray = {
   "field_1": "lorem ipsum",
   "field_2": [1,2,6]
};

If you do console.log now, you'll get this:

field_1      "lorum ipsum"
field_2
    0        1
    1        2
    2        6

Hope that helps.

Post a Comment for "Js Associative Object With Duplicate Names"