Reference an object, based on a variable with it's name in it
- by James G
I'm looking for a way to reference an object, based on a variable with it's name in it.
I know I can do this for properties and sub properties:
var req = {body: {jobID: 12}};
console.log(req.body.jobID); //12
var subProperty = "jobID";
console.log(req.body[subProperty ]); //12
var property = "body";
console.log(req[property][subProperty]); //12
is it possible for the object itself?
var req = {body: {jobID: 12}};
var object = "req";
var property = "body";
var subProperty = "jobID";
console.log([object][property][subProperty]); //12
or
console.log(this[object][property][subProperty]); //12
Note: I'm doing this in node.js not a browser.
Here is an exert from the function:
if(action.render){
res.render(action.render,renderData);
}else if(action.redirect){
if(action.redirect.args){
var args = action.redirect.args;
res.redirect(action.redirect.path+req[args[0]][args[1]]);
}else{
res.redirect(action.redirect.path);
}
}
I could work around it by changing it to this, but I was looking for something more dynamic.
if(action.render){
res.render(action.render,renderData);
}else if(action.redirect){
if(action.redirect.args){
var args = action.redirect.args;
if(args[0]==="req"){
res.redirect(action.redirect.path+req[args[1]][args[2]]);
}else if(args[0]==="rows"){
rows.redirect(action.redirect.path+rows[args[1]][args[2]]);
}
}else{
res.redirect(action.redirect.path);
}
}