Skip to content

Instantly share code, notes, and snippets.

@mikeumus
Last active September 17, 2018 13:55
Show Gist options
  • Save mikeumus/e94b57fab07d5c49f20479d34a09b812 to your computer and use it in GitHub Desktop.
Save mikeumus/e94b57fab07d5c49f20479d34a09b812 to your computer and use it in GitHub Desktop.

Revisions

  1. mikeumus revised this gist Sep 17, 2018. No changes.
  2. mikeumus created this gist Sep 17, 2018.
    42 changes: 42 additions & 0 deletions deep-search.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    function pullKeys(obj, results, path) {
    var breadcrumb = path;
    for (var prop in obj) {
    if (obj.hasOwnProperty(prop)) {
    // path = breadcrumb ? breadcrumb ? path : prop : path;
    // console.log('\n\n path: \n', path, '\n\n');
    if (typeof obj[prop] === "object") {
    path = path ? breadcrumb ? breadcrumb += `.${prop}` : path += `.${prop}` : prop;
    pullKeys(obj[prop], results, path);
    } else {
    var innerObj = {};
    innerObj[path] = obj[prop];
    results.push(innerObj);
    }
    path = breadcrumb ? breadcrumb : path;
    console.log('\n\n path: \n', path, '\n\n');
    }
    }
    // console.log('\n\n breadcrumb: \n', breadcrumb, '\n\n');
    path = '';
    }

    function deepFind(results, target) {
    var found = [];
    results.forEach( function(item) {
    if ( Object.values(item)[0] === target ) {
    found.push(item);
    }
    });
    return found;
    }

    function deepSearch(obj, target) {
    var results = [];
    pullKeys(obj, results);
    return deepFind(results, target);
    }

    var testObj1 = {
    notAnObject: 'just a string',
    iamObject: { now: 'what?' }
    }