I have a variable that takes its value from the current object's ID attribute, it will always look something like filtercolor-red:
$('.facet-options-list li input[id*=filtercolor]').each(function() {
var filterColor = $(this).attr('id');
...
});
I also have an array that lists possible ID's and a corresponding HEX code:
var activeFilterBg;
var filterBgColor = [];
filterBgColor = {
filtercolor-black: '#171710',
filtercolor-blue: '#4C94B6',
filtercolor-brown: '#50443D',
filtercolor-gold: '#F6D069',
filtercolor-green: '#96B14D',
filtercolor-grey: '#A8AAA5',
filtercolor-orange: '#DB5E46',
filtercolor-pink: '#E78EB1',
filtercolor-purple: '#59547E',
filtercolor-red: '#D22200',
filtercolor-silver: '#EBEBEB',
filtercolor-white: '#FFF'
};
What I'd like to do is take filterColor and assign activeFilterBg the appropriate HEX code from filterBgColor. I could do this with a switch, but that seems kind of sloppy and gives a lot of room for mistakes in the future.
Do I have an option to somehow lookup the correct key and then assign a variable based upon it?
var color = filterBgColor[filterColor]var filterBgColor = [];) and then throwing it away and assigning an Object to the same variable (filterBgColor = { ... }). It's important to know the distinction between Arrays and Objects in JavaScript. You should only use Arrays when you want numeric keys, e.g.var a = ["A", "B", "C"]; console.log(a[0]); // => "A". Otherwise you should use an Object:var o = { foo: "X", bar: "Y", ... }; console.log(o.foo); // => "X"