【发布时间】:2017-08-08 00:16:11
【问题描述】:
我在 ES6 中尝试使用代理,试图在一个对象上创建一个无限可链接的代理(从https://jsonplaceholder.typicode.com/users 获得),如果找不到该属性,它应该返回 empty{}。
我尝试将此功能实现到第二级(例如,user.address.geo)。 编辑:更新了检查道具值类型的代码
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"
}];
我想出了下面的代码
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)
});
此代码的输出不吸引人,它返回 undefined 而不是空的{} 对象
{ street: 'Kulas Light',
suite: 'Apt. 556',
city: 'Gwenborough',
zipcode: '92998-3874' }
undefined
我这样做了几次,仍然得到相同的结果。我错过了什么吗?
【问题讨论】:
-
checkJSON- 什么?这看起来非常复杂,根本不清楚该函数应该做什么。 -
检查值是否为对象类型:我从stackoverflow.com/questions/4295386/…得到的
-
不寒而栗。不要那样做。您周围没有任何 JSON,因此您不需要对任何内容进行字符串化/解析。只需测试
typeof x == "object"。 -
更新了代码,仍然无法实现所需的功能
标签: javascript proxy ecmascript-6