Skip to content

Instantly share code, notes, and snippets.

@crates
Created March 17, 2020 02:03

Revisions

  1. crates created this gist Mar 17, 2020.
    36 changes: 36 additions & 0 deletions safeObjectProxy.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    const proxyObj = (obj) {
    return new Proxy(obj, {
    get: function(target, name) {
    const result = target[name];
    if (!!result) {
    return (result instanceof Object)? proxyObj(result) : result;
    }
    return proxyObj({});
    }
    });
    };

    // Usage:
    const jane = {
    name: 'Jane',
    age: 35
    };
    const john = {
    name: 'John',
    address: {
    street: '7th Avenue',
    city: 'Ecmaville',
    zipCode: '23233'
    },
    sister: jane,
    age: 28
    };
    var proxyPerson = proxyObj(john);
    console.log(proxyPerson.name); // --> "John"
    console.log(proxyPerson.address.street); // --> "7th Avenue"
    console.log(proxyPerson.sister.name); // --> "Jane"
    console.log(proxyPerson.sister.address); // --> {}
    console.log(proxyPerson.sister.address.street); // --> {}

    // See also:
    // https://gist.github.com/dakaraphi/6a87168db66fd8f032d2