How to use javascript proxy for nested objects

Aflred picture Aflred · Dec 23, 2016 · Viewed 16.2k times · Source

I have this code in js bin:

var validator = {
  set (target, key, value) {
    console.log(target);
    console.log(key);
    console.log(value);
    if(isObject(target[key])){

    }
    return true
  }
}


var person = {
      firstName: "alfred",
      lastName: "john",
      inner: {
        salary: 8250,
        Proffesion: ".NET Developer"
      }
}
var proxy = new Proxy(person, validator)
proxy.inner.salary = 'foo'

if i do proxy.inner.salary = 555; it does not work.

However if i do proxy.firstName = "Anne", then it works great.

I do not understand why it does not work Recursively.

http://jsbin.com/dinerotiwe/edit?html,js,console

Answer

Michał Perłakowski picture Michał Perłakowski · Dec 23, 2016

You can add a get trap and return a new proxy with validator as a handler:

var validator = {
  get(target, key) {
    if (typeof target[key] === 'object' && target[key] !== null) {
      return new Proxy(target[key], validator)
    } else {
      return target[key];
    }
  },
  set (target, key, value) {
    console.log(target);
    console.log(key);
    console.log(value);
    return true
  }
}


var person = {
      firstName: "alfred",
      lastName: "john",
      inner: {
        salary: 8250,
        Proffesion: ".NET Developer"
      }
}
var proxy = new Proxy(person, validator)
proxy.inner.salary = 'foo'