Reputation: 9007
I want to find object property dynamically from array that map to property location.
Example
Var objectA = { a:{b:1} };
Var Names = ['objectA','a','b'];
Howa can i get value of b
by looping over array Names ?
Upvotes: 0
Views: 50
Reputation: 3627
Assuming objectA
is available in the global scope (window.objectA
), you could do something like this:
names.reduce(function (memo, value) {
return memo[value];
}, window)
For any other "non-global" variable, you can create a getter function that takes the variable and the path (an array just like your names
, but without the first value) as a parameter:
function nestedValue(obj, path) {
return path.reduce(function (memo, value) {
return memo[value];
}, obj);
}
BTW, please note that Array.prototype.reduce()
is a ES2015 feature, so if you need to be compatible with older browsers, you would have to use some variation of for
loop for this task.
You could also check out lodash.get for more sophisticated solution (if you're willing to include it in your project).
Upvotes: 2
Reputation: 9413
You can use eval: eval(Names.join('.'))
Can use this with nodejs
inside a sandbox:
const util = require('util');
const vm = require('vm');
const objectA = { a: { b: 1 }};
const Names = ['objectA', 'a', 'b'];
const sandbox = { objectA: objectA, Names: Names };
vm.createContext(sandbox);
for (var i = 0; i < 10; ++i) {
vm.runInContext("var result = eval(Names.join('.'))", sandbox);
}
console.log(util.inspect(sandbox));
/* {
objectA: { a: { b: 1 } },
Names: [ 'objectA', 'a', 'b' ],
result: 1
}
*/
Upvotes: 1
Reputation: 36521
To do this without eval would require you store ObjectA
as a property of another object that you could iterate over using the array keys. eval
will work in this case though:
objectA = { a: { b: 1 }}
names = ['objectA', 'a', 'b']
alert(eval(names.join('.')))
Upvotes: 0