What about link: 'tree.options[0].options[0]'
then eval(path.to.link)
?
Following samples were tested with Chrome only. Same tree for all :
var tree = { level1: [{ key: 'value' }] };
No eval
function resolve(root, link) {
return (new Function('root', 'return root.' + link + ';'))(root);
}
var value = resolve(tree, path.to.link);
Fallback to window
function resolve(root, link) {
return (new Function(
'root', 'return root.' + (link || root) + ';'
))(link ? root : window);
}
resolve(tree, 'level1[0].key'); // "value"
resolve('tree.level1[0].key'); // "value"
Catching errors
The try/catch block prevents broken links from throwing errors.
function resolve(root, path) {
try {
return (new Function('root', 'return root.' + path + ';'))(root);
} catch (e) {}
}
resolve(tree, 'level1[0].key'); // "value"
resolve(tree, 'level1[1].key'); // undefined
Using custom path format
The good part here is that we can pass either an object or an array as root
. Also note that we can replace the slash in path.split('/')
with any char of our choice.
function resolve(root, path) {
path = '["' + path.split('/').join('"]["') + '"]';
return (new Function('root', 'return root' + path + ';'))(root);
}
resolve(tree.level1, '0/key'); // "value"
resolve(tree, 'level1/0/key'); // "value"
resolve(tree, 'level1/0'); // Object {key: "value"}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…