Ben Ben - 4 months ago 11
jQuery Question

Dynamically create parameter from array in jQuery

I'm using this plugin on my website, which works great. You can pass a parameter for state specific styles, it looks like this:

$('#map').usmap({

showLabels: false,

stateStyles: {

fill : '#ffffff',

stroke : '#4f4f4f',

'stroke-width' : 4,

},

stateHoverStyles: {

fill : '#ffffff'

},

stateSpecificStyles: {

'IN': {

fill : '#84b8e7'

},

'CA': {

fill : '#84b8e7'

},

'TX': {

fill : '#84b8e7'

}

},

stateSpecificHoverStyles: {

'IN': {

fill : '#0972ce'

},

'CA': {

fill : '#0972ce'

},

TX': {

fill : '#0972ce'

}

}

});


I would like to fill in those state styles dynamically from an array that looks like ["CA", "IN", "TX"]. Is this possible?

Answer

If you're just looking for a way to create an object that looks like that, this snippet will do it for you. Let us know more about what you have/need, and I can expand this.

var arr = ['CA', 'IN', 'TX'], // Your state vars
    output = [];

arr.forEach(function(el) {
  output[el] = {
    fill: '#000000' // Could come from the same array, if needed
  };
)};
            
console.log(output);