簡體   English   中英

使用Javascript的語法糖來訪問對象屬性

[英]Javascript's syntactic sugar for accessing object properties

我有一個“結果”對象,我想匯總這些嵌套屬性的值。

是否存在一種優雅的方法來分配這兩個屬性的值( 如果它們存在) ,否則拋出並出錯? 我發現自己寫了一些很長的代碼來完成這樣的簡單操作。

謝謝

host: result["ServerCA"]["_"],
database: result["DBId"]["_"]

EDIT1-更多信息

我的代碼構造了一個具有兩個屬性hostdatabase result對象是一個包含一些信息的JSON。 我不能保證JSON實際上將包含這兩個屬性_ServerCA下和_DBId下。 實際上,我不確定在result對象中是否定義了ServerCADBId

因此,我試圖驗證這些屬性是否存在,並將它們的值分配給我自己對象的兩個屬性hostdatabase

我如何以最簡單的方式編寫此代碼,而不是編寫2個雙IF語句?

謝謝...

您可以編寫一個輔助函數來執行此操作,例如:

function getOrThrow(obj, keys) {
    return keys.reduce(function(result, key) {
        if (!(typeof result === 'object') || !(key in result)) {
            throw new Error("property " + key + " does not exists");
        }
        return result[key];
    }, obj);
}

var result = {
    ServerCA: {
        _: "whatever"
    }
};

console.log(getOrThrow(result, ["ServerCA", "_"])); // whatever
console.log(getOrThrow(result, ["ServerCA", "_", "other"])); // throws error

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM