Proxy

create proxy for object

by Vladymyr Shevchuk

JavaScript

const obj   = { a: 1, b: { c: 2, d: null, e: { f: 1 } }};
  const config = { a: 2, b: { d: 3, e: { f: 5, g: 12 } }};
  const isObject = obj => Object.prototype.toString.call(obj) === "[object Object]";

  const getProxy = (obj, config) => {
    const getValue = (obj, config) => {
      return new Proxy(obj, {
        get(target, prop) {
          if (isObject(target[prop])) {
            return getValue(target[prop], config[prop]);
          } else {
            return target[prop] || config[prop];
          }
        }
      })
    };

    return getValue(obj, config);
  };

  const proxy = getProxy(obj, config);
  const {a, b} = proxy;

  console.error('a', a);
  console.error('b', b);
  console.error('c', b.c);
  console.error('d', b.d);
  console.error('g', b.e.g);