What are the best ways to reference branches of a JSON tree structure?

前端 未结 1 785
谎友^
谎友^ 2020-12-02 02:47

So I\'ve got a JSON file that gets parsed into an object in Javascript. I know what you\'re thinking: lucky guy. The JSON is essentially a flow diagram in a big tree form. H

相关标签:
1条回答
  • 2020-12-02 03:25

    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"}
    
    0 讨论(0)
提交回复
热议问题