我正在試驗ES6中的代理,試圖在對象上創建無限可鏈接的代理(從https://jsonplaceholder.typicode.com/users獲得),如果找不到prop,則返回空{}
。在嵌套對象上實現代理
我試圖實現此功能高達第二級(例如user.address.geo)。 編輯:用於檢查類型屬性內容的更新代碼
let users = [{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "[email protected]",
"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": "[email protected]",
"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
我做了這幾次,仍然得到相同的結果。我錯過了什麼嗎?
[有沒有這樣的事,作爲一個「JSON對象」](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) –
'checkJSON' - 什麼?這看起來非常令人費解,根本不清楚該功能應該做什麼。 – Bergi
檢查值是否是類型對象:我從http://stackoverflow.com/questions/4295386/how-can-i-check-if-a-value-is-a-json-object – NikhilGoud