簡體   English   中英

Javascript在對象中返回Null值

[英]Javascript returning Null value in object

我正在使用以下代碼來調用API並返回結果:

api.jobs.all(function(response) {

const obj = response.data.map(function(item) {
    return [item.id, item.billed.amountString];

});
});

使用以下JSON:

{
  "data": [
  {
     "id": 2090170,
     "deadline": null,
     "jobId": {
        "id": 1644
     },
     "billed": {
        "amountString": 200,
        "currencyType": "CAD"
     }
    },
    {
     "id": 2090171,
     "deadline": null,
     "jobId": {
        "id": 1645
     },
     "billed": {
        "amountString": 400,
        "currencyType": "USD"
     }
}]}

該代碼運行正常,在大多數情況下,我獲得了良好的結果,但以下情況除外: billed.amountString

我不斷收到以下錯誤:

TypeError:無法讀取null的屬性'amountString'

誰能看到為什么這將返回null?

另外,有沒有一種方法可以循環遍歷API調用並強制其執行以下操作:

If .amountString === null, .amountString = "";

 var response = { "data": [ { "id": 2090170, "deadline": null, "jobId": { "id": 1644 }, "billed": { "amountString": 200, "currencyType": "CAD" } }, { "id": 2090171, "deadline": null, "jobId": { "id": 1645 }, "billed": { "amountString": 400, "currencyType": "USD" } }]}; const obj = (response.data).map(function(item) { return [item.id, item.billed.amountString]; }); console.log(obj); 

您可以使用lodash庫。 lodash方法get可以用於嘗試訪問對象字段。 如果不存在,則可以指定默認返回值。 參見https://lodash.com/

// This will try to access item.billed.amountString
// If an item does not exist anywhere along the way
// it will return the default.

// _.get( OBJECT, PATH, DEFAULT )
_.get(item, ['billed', 'amountString'], '')

暫無
暫無

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

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