Skip to content

Instantly share code, notes, and snippets.

@cdmckay
Created July 15, 2015 03:46
Show Gist options
  • Select an option

  • Save cdmckay/6ac36defdc01d39080fa to your computer and use it in GitHub Desktop.

Select an option

Save cdmckay/6ac36defdc01d39080fa to your computer and use it in GitHub Desktop.

Revisions

  1. cdmckay created this gist Jul 15, 2015.
    16 changes: 16 additions & 0 deletions elvis.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,16 @@
    function elvis(object, path) {
    return path ? path.split('.').reduce(function (value, key) {
    return value && value[key];
    }, object) : object;
    }

    // Example
    var o = { a: { b: 1, c: 2 }, d: 3 };
    elvis(o, 'a');
    // = { b: 1, c: 2 }
    elvis(o, 'a.b');
    // = 1
    elvis(o);
    // = { a: { b: 1, c: 2 }, d: 3 }
    elvis(o, 'x');
    // = undefined