When working with this JavaScript object, the goal is to access its nested properties dynamically using a method that begins with 'get' followed by a CamelCased attribute name (provided that the attribute is defined in the initial object).
While I am aware that achieving this may involve utilizing a Proxy object along with recursion, any additional insights or suggestions are greatly appreciated.
Thank you for your assistance!
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
I attempted to implement this functionality with the following code snippet, but it appears not to work as intended for accessing 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"