Given this JavaScript object, I want to access their nested properties via dynamic method starting with ‘get’ + a CamelCased attribute name (of course the attribute must be defined in the inital object)
As far as I know, this can be achieved by using a Proxy object + recursion, but I need your input anyway.
Best regards!
function Order() {
this.no = 'n1234';
this.info = {
customer: {
ID: 'c1234'
address: {
//...
shiping: {
// ...
}
}
}
}
}
var order = new Order();
// The expected result should be:
// order.no = order.getNo()
// order.info = order.getInfo()
// order.info.customer or order.info.getCustomer() or order.getInfo().customer or order.getInfo().getCustomer()
// and so on for all nested attributes
This is the snippet I prepared, but it doesn’t seem to work for nested properties.
function createProxy(obj) {
return new Proxy(obj, {
get(target, prop) {
if (typeof target[prop] === 'object' && target[prop] !== null) {
return createProxy(target[prop]);
}
if (prop.startsWith('get')) {
const propName = prop.charAt(3).toLowerCase() + prop.slice(4);
if (target[propName] !== undefined) {
return () => target[propName];
}
}
return target[prop];
},
});
}
function Order() {
const properties = {
no: 'n1234',
info: {
customer: {
ID: 'c1234'
}
}
};
return createProxy(properties);
}
var order = new Order();
// order.getInfo().customer - { ID: 'c1234' }
// order.getInfo().getCustomer() - TypeError: order.getInfo().getCustomer is not a function"
2
Answers
Here is the working solution. Thanks to @Barmar and Alexander Nenashev
Some tweaks would help, the main is to return a proxy from
getXXX()
calls too: