Reputation: 49
I have separate javascript files to load custom objects; these objects are designed to extend some default parameters when the main function is read
they each look like
var str1= { path:'url1:, var1:5};
var str2= { path:'url2:, var1:3};
etc...
I have an array of strings(that is generated from loading an rss page) and i want to return the object based on if its name matches the object name. hardcoding it would kind of defeat the purpose
Upvotes: 0
Views: 214
Reputation: 32598
var map = { "string1": { path: "url1", var1:5},
"string2": { path: "url2", var1:3} };
...
var url = map[yourstring].path;
Upvotes: 0
Reputation: 75317
You can use the square bracket notation to refer to object properties whose key name is held in a variable:
var key = 'path';
var str1 = { path: 'url', var1: 1};
var value = str1[key]; // value == 'url';
You can also do:
var str1 = 'a';
var str2 = 'b';
var key = 'str1';
var value = window[key]; // value == 'a';
Upvotes: 0
Reputation: 19339
Take a look at this question. It shows how to reference objects by using strings. The only difference I can see is that rather than starting with the window
object, you would start at whatever object defines your current scope (e.g. this
).
Upvotes: 1