Pjotr Raskolnikov
Pjotr Raskolnikov

Reputation: 1688

Understing loops with node

In node js i have a function that iterates trough an array to fill another element. Some times some proprerties are undefined, how can that be? For example i get "cannot read property formattedPrice of undefined". What is wrong with a for loop on node?

for (var i = 0; i < 10; i++) {
    //console.log(JSON.stringify(item.SmallImage));
        message.attachment.payload.elements[i] = {
            "title":items[i].ItemAttributes.Title,
            "image_url": items[i].LargeImage.URL,
            "subtitle":items[i].ItemAttributes.ListPrice.FormattedPrice,
            "default_action": {
            "type": "web_url",
            "url": "https://www.google.it",
            "messenger_extensions": true,
            "webview_height_ratio": "tall",
            "fallback_url": "https://www.google.it"
            },
            "buttons":[
                {
                  "type":"web_url",
                  "url":"https://www.google.it",
                  "title":"View Website"
              },{
                  "type":"postback",
                  "title":"Start Chatting",
                  "payload":"DEVELOPER_DEFINED_PAYLOAD"
              }             
          ]      
        }
    //sendMessage( senderId, {text: item.ItemAttributes.Title+" PREZZO**:"+item.ItemAttributes.ListPrice.FormattedPrice});
    }

Upvotes: 1

Views: 43

Answers (1)

Pat Needham
Pat Needham

Reputation: 5918

cannot read property formattedPrice of undefined means the object from which you were trying to access formattedPrice, items[i].ItemAttributes.ListPrice, is null/undefined.

To prevent that error from occurring, you should include some validation before assigning the value to message.attachment.payload.elements[i].

for (var i = 0; i < 10; i++) {
    var subtitle = "N/A";
    if (items[i].ItemAttributes.ListPrice == null) {
        subtitle = items[i].ItemAttributes.ListPrice.FormattedPrice;
    }
    message.attachment.payload.elements[i] = {
        ...
        "subtitle": subtitle, // will now show as "N/A" instead of causing program to crash
        ...
    };
}

Another thing to consider is that in the for loop, instead of having the condition as i < 10, replace it with i < items.length, unless you are sure the items list will always contain 10 or more elements.

Upvotes: 1

Related Questions