I'm experimenting with Proxies in ES6, was trying to create an infinitely chainable Proxy on an object(got from https://jsonplaceholder.typicode.com/users) which should return empty{}
if the prop is not found.
I tried to implement this functionality up to 2nd level(e.g, user.address.geo). EDIT: Updated code for check type of prop value
let users = [{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874"
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org"
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna@melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771"
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net"
}];
I came up with below code
var handler = {
get: function (target, name) {
return name in target ?
target[name] : {};
}
};
let pusers = users.map(item => {
let pitem = new Proxy(item, handler);
Reflect.ownKeys(pitem).map(prop => {
pitem[prop] = (typeof pitem[prop] == 'object') ? new Proxy(pitem[prop], handler) : pitem[prop];
})
return pitem;
});
pusers.map(u => {
console.log(u.address);
console.log(u.contact.city)
});
Output for this code is not appealing, it is returning undefined
instead of an empty{}
object
{ street: 'Kulas Light',
suite: 'Apt. 556',
city: 'Gwenborough',
zipcode: '92998-3874' }
undefined
I did this few times and still getting the same result. Am I missing something?