Fabio Fabio - 1 month ago 6
jQuery Question

How to use input value as array index

I'm actaully out of ideas.
I've been reading around about this problem but I didn't find any answer that suits my need. So here is the scenario

I have some inputs where I get a value by their

id


<input type="hidden" id="name" value="Taco house" />
<input type="hidden" id="pin" value="Mexican" />


And I try to use the value as
index
to build an array

var name = $('#name').val();
var pin = $('#pin').val();

markersData = {
pin: [ //here it should put 'Mexican' instead it puts 'pin'
{
name: name,
location_latitude: 43.5391318,
location_longitude: 10.3020171,
//other nodes here
}
]
};


If I print
pin
variable before passing to the array it prints its actual value, but once I pass to the array the value is lost and the index became pin.

For sure this is an obvious question but since I'm not that good in jquery I need some help.

Answer

This should do the trick :

var name = $('#name').val();
var pin = $('#pin').val();
markersData = {};
markersData[pin] = [{
    name: name,
    location_latitude: 43.5391318,
    location_longitude: 10.3020171,
    //other nodes here
}];

Your way won't work, because the parser consider pin as a string, not as the content of your "pin" variable. Neither can you do markersData.pin for the same reason.

As far as I know (I might be wrong), the only way to do this is to use square brackets, which might be a bit confusing since it looks like adding an index to an array. Hope this helps

Comments