Aaron
Aaron

Reputation: 1583

Accessing both JavaScript Object key and value

I'm writing a mapper which spots identifying words in a string and replaces them with another word. In my case a location identifier with the actual directory location.


My Problem is on line 8 : str.replace(x.toString(), keys[x]);

The value x is the value as expected but keys[x] returns undefined.

var keys = {
   "$processes"        : "/processes",
   "$local_resources"  : "/feeds/local"
};

function CoreRoute(str){
   for (var x in keys){
      str.replace(x, keys[x]);
   }
   return str;
}

I am developing in the node enviroenment. But I'm pretty sure it's a mistake with my logic.

Upvotes: 1

Views: 377

Answers (1)

Eugene
Eugene

Reputation: 1730

Strings are immutable in Javascript, so String.replace() can't modify str, it returns a new String with the replacement performed. Change

str.replace(x, keys[x]);

to

str = str.replace(x, keys[x]);

End code:

var keys = {
    "$processes"       : "/processes",
    "$local_resources" : "/feeds/local"
};

function CoreRoute(str) {
    for (var x in keys) {
        str = str.replace(x, keys[x]);
    }
    return str;
}

Upvotes: 1

Related Questions