2017-05-05 76 views
0

我嘗試將函數參數值作爲對象屬性選擇器檢索到.filter()方法中時出現問題。Angular:無法檢索函數參數值作爲對象屬性選擇器

這是我的代碼:

myFunction(property, value) { 
    function myFilter(obj) { 
     return obj.details.name == value; 
    } 
    return this._http.get(this.Url).map((response: Response) => response.json().filter(myFilter)); 
} 

我想return obj.property == value;更換return obj.details.name == value;

obj。 屬性是我的函數myFunction(屬性,值)的參數。 參數值工作正常,並很好地檢索。

這就是我想要的:

getFilteredFMsBy(property, value) { 
    function specificFilter(obj) { 
     return obj.property == value; 
    } 
    return this._http.get(this.Url).map((response: Response) => response.json().filter(specificFilter)); 
} 

如果我定義的屬性在函數的值,同樣的情況。它不起作用:

getFilteredFMsBy(property, value) { 
    property = "details.name"; 
    function specificFilter(obj) { 
     return obj.property == value; 
    } 
    return this._http.get(this.Url).map((response: Response) => response.json().filter(specificFilter)); 
} 

任何想法?

+0

的obj [屬性]將讓你訪問的時候,你不知道一個屬性是直接的名稱。 – Sebastian

回答

1

好像你需要訪問的對象[道具] [PROP2]給出的對象和字符串 「prop.prop2」

從這樣的回答:Javascript: Get deep value from object by passing path to it as string你可以做deepFind:

function deepFind(obj, path) { 
    var paths = path.split('.') 
    , current = obj 
    , i; 

    for (i = 0; i < paths.length; ++i) { 
    if (current[paths[i]] == undefined) { 
     return undefined; 
    } else { 
     current = current[paths[i]]; 
    } 
    } 
    return current; 
} 

然後做

getFilteredFMsBy(property, value) { 
    property = "details.name"; 
    function specificFilter(obj) { 
     return deepFind(obj, property) == value; // <-- use it here 
    } 
    return this._http.get(this.Url).map((response: Response) => response.json().filter(specificFilter)); 
} 
+0

感謝隊友。有用 :) – Jonathan

0

這個怎麼樣?

getFilteredFMsBy(property: string, value:any) { 
    return this._http.get(this.Url).map((response: Response) => response.json().filter((obj) => { return obj[property] == value; })); 
} 
相關問題