I have a group of values that need to be transformed into new values using a legend. The process might sound confusing at first, but it will become clear shortly. To achieve this, I've relied on associative arrays or objects in JavaScript to serve as my legend.
This method can be applied to individual strings, arrays like the one below, or even objects.
var legend = {
"html": "html5",
"css2": "css3",
"javascript": "jquery"
}
var old_array = new Array("html", "css2", "javascript");
var new_array = [];
max = old_array.length;
// iterate through original array values
for(i=0;i<max;i++){
for(var val in legend){
// loop through legend values and convert if there's a match
if(old_array[i] === val){
new_array[i] = legend[val];
}
}
}
console.log(new_array);
document.write(new_array);
If you run this code in firebug or jsfiddle, you'll see a new array with the updated values.
I opted for an object/associative array as my legend because of its scalability. If new values require conversion, it's easy to add them. This method is versatile and works for converting individual strings, arrays like above, or objects and their keys or values.
Is this the best approach for value conversion? Are there any other factors to consider? In PHP, which is another language I frequently use, could the same concept of using an associative array apply?
Thank you for your guidance and advice!
Cheers!