Jim Dover
Jim Dover

Reputation: 623

Javascript returning Null value in object

I am using the following code to call an API and return results:

api.jobs.all(function(response) {

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

});
});

With the following 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"
     }
}]}

The code is working fine, for the most part I am getting back good results, with the exception of: billed.amountString

I keep getting the following error:

TypeError: Cannot read property 'amountString' of null

Can anyone see why this would be returning null?

Also, is there a way in which I could loop through the API call and force it to do the following:

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

Upvotes: 0

Views: 1723

Answers (2)

Devendra Lattu
Devendra Lattu

Reputation: 2802

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

Upvotes: 1

Pearman
Pearman

Reputation: 1068

You could use the library lodash. The lodash method get can be used to try and access an object field. If it does not exist you can specify a default return value. See 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'], '')

Upvotes: 0

Related Questions