Skip to content

Instantly share code, notes, and snippets.

@brendt
Last active August 29, 2015 14:26
Show Gist options
  • Save brendt/91b50ff795a0e3581553 to your computer and use it in GitHub Desktop.
Save brendt/91b50ff795a0e3581553 to your computer and use it in GitHub Desktop.
Traverse JSON
// function
function search(target, path) {
    var index = path.match(/^[\w]+/);
    if (target[index] === undefined) {
        return undefined;
    }

    path = path.replace(/^[\w]+\./, '');
    if (path == index) {
        return target[index];
    }

    return search(target[index], path);
}

// prototype
Object.prototype.search = function(path) {
    var index = path.match(/^[\w]+/);
    if (this[index] === undefined) {
        return undefined;
    }

    path = path.replace(/^[\w]+\./, '');
    if (path == index) {
        return this[index];
    }

    return this[index].search(path);
};

Example

var foo = {
    bar : {
        name : 'foobar',
    },
    baz : {
        name : 'foobaz',
        children : [
            'baza',
            'bazu',
            'bazo',
        ],
        category : {
            name : 'bazcat',
        }
    }
}

console.log(foo.search('bar.name')); // 'foobar'
console.log(search(foo, 'bar.names')); //undefined
console.log(foo.search('baz.children')); // array
console.log(foo.search('baz.children')[0]); // 'baza'
console.log(foo.search('baz.children')[9]); // undefined
console.log(search(foo, 'baz.category')); // Object
console.log(foo.search('baz.category.name')); // 'bazcat'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment