Reference an object, based on a variable with it's name in it
Posted
by
James G
on Stack Overflow
See other posts from Stack Overflow
or by James G
Published on 2014-08-21T21:14:50Z
Indexed on
2014/08/21
22:20 UTC
Read the original article
Hit count: 146
JavaScript
|node.js
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);
}
}
© Stack Overflow or respective owner