https://stackoverflow.com/a/41300128
↑ completely based on this code
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); // salary
console.log(value); // foo
// ⭐ Is it possible to get "inner" here?
return true
}
}
var person = {
firstName: "alfred",
lastName: "john",
inner: {
salary: 8250,
Proffesion: ".NET Developer"
}
}
var proxy = new Proxy(person, validator)
proxy.inner.salary = 'foo'
As I wrote in code with star emoji, is it possible to get parent property name of nested object in set method of Proxy object?
And any alternative solutions you have?
Yes, it is possible by creating new proxy handlers where each keeps the full path which was used to access the property. This is essentially a recursive technique to keep data during recursive calls:
It will also work if you separate the access and setting to multiple expressions:
Even if you have circular dependencies:
Or otherwise have multiple paths to a property, this proxy will keep the path that was used to access such property: