Javascript在对象中返回Null值

时间:2017-05-02 22:11:11

标签: javascript api 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 = "";

2 个答案:

答案 0 :(得分:1)

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);

答案 1 :(得分:0)

您可以使用库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'], '')
相关问题