0

So I have a bunch of values I need to convert to new values. Basically with a legend. It'll make sense in a second. So far, I've been using associative arrays, or in the context of javascript, objects as my legend.

My use is applicable to individual strings, arrays as I have blow, or objects.

var legend = {
    "html": "html5",
    "css2": "css3",
    "javascript": "jquery"  
}

var old_array = new Array("html", "css2", "javascript");
var new_array = [];

max = old_array.length;

// loop through values in original array
for(i=0;i<max;i++){
    for(var val in legend){
            // looping through values in legend.  If match, convert
        if(old_array[i] === val){
            new_array[i] = legend[val];
        }
    }
}
console.log(new_array);
document.write(new_array);

If you paste that into firebug or jsfiddle, it'll show a new array with the converted values.

I decided on object/associative array as my legend because it's easy to expand in case new values need to be converted. I think it's pretty robust. And it works for converting an individual string, an array as shown above, or an object, either the keys or the values.

For converting values, is it the best method? Any considerations? For php, as it's the only other language I use regularly, would the same concept, with an associative array, also be used?

Thanks so much for your help and advice!

Cheers!

David Hobs
  • 4,351
  • 2
  • 21
  • 22

1 Answers1

3

You're not using the power of the object as there is no reason to loop through the object. It already has keys that you can just lookup directly like this:

var legend = {
    "html": "html5",
    "css2": "css3",
    "javascript": "jquery"  
}

var old_array = new Array("html", "css2", "javascript");
var new_array = [];

max = old_array.length;

// loop through values in original array
for(var i=0;i<max;i++){
    // see if array value is a key in the legend object
    if ([old_array[i] in legend) {
        new_array.push(legend[old_array[i]]);
    }
}
console.log(new_array);
document.write(new_array);

I also changed it to use new_array.push() so you don't end up with an array with some undefined values, but I'm not really sure what type of end result you're trying to end up with.

jfriend00
  • 683,504
  • 96
  • 985
  • 979