Cyph Cyph -4 years ago 241
Node.js Question

es6 proxy safe deep object

I wrote a small wrapper to return undefined in place of typeError when accessing properties that don't exist using a Proxy. Here is the code:

function proxify(event) {
var proxy = new Proxy(event, {
get: function (target, property) {
if (property in target) {
return target[property];
} else {
return '';
}
}
}
});
return proxy;
}


This works when a property is missing 1 level deep.
For example, assuming obj.something does not exist:

obj.something.else


will return undefined

But if the object property is deep nested

obj.something.else.deeper


I receive a typeError

My question is how do I extend the function above to work on deep nested objects?

Thx

Answer Source

You need to wrap the return value in your proxify function:

function proxify(event) {
  return isPrimitive(event) ? event : new Proxy(event, { get: getProp });
}
function isPrimitive(v) {
  return v == null || (typeof v !== 'function' && typeof v !== 'object');
}
function getProp (target, property) {
  if (property in target) {
    return proxify(target[property]);
  } else {
    return proxify({});
  }
}

In all honesty, you're probably better off using something like lodash's _.get() or ramda's R.path(). There's no way to know from the first getProp() call how many layers deep the evaluation is going to go, so it has to always return a primitive value or a "truthy" Proxy instance so that the next property access can be intercepted (if one happens). The _.get() method on the other hand takes a string so it can immediately know from the initial invocation that you're only trying to access down so many levels.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download