Search code examples
javascriptnode.jsfacebookfacebook-messenger-bot

Loop through facebook messengger bot elements


I have the code below

bodyObj['providers'].map(service => {
                // console.log(service.name)
            })
            const campaigns = {
                "attachment": {
                    "type": "template",
                    "payload": {
                        "template_type": "generic",
                        "elements": [{
                            "title": bodyObj['providers'][0].name,
                            "image_url": bodyObj['providers'][0].coverImage.toString(),
                            "subtitle": bodyObj['providers'][0].location.textLoc,
                            "buttons": [{
                                "type": "postback",
                                "payload": config.VIEW_SERVICES,
                                "title": "Select"
                            }]
                        },
                        {
                            "title": bodyObj['providers'][1].name,
                            "image_url": bodyObj['providers'][1].coverImage.toString(),
                            "subtitle": bodyObj['providers'][1].location.textLoc,
                            "buttons": [{
                                "type": "postback",
                                "payload": config.VIEW_SERVICES,
                                "title": "Select"
                            }]
                        }
                        ]
                    }
                }
            }

but i want to find a way how i can loop through bodyObj object and display each of the element details in the facebook messenger bot template instead of what i have done above . I would be grateful for the help, thanks in advance


Solution

  • Just use map inside elements property:

    const campaigns = {
     "attachment": {
       "type": "template",
       "payload": {
          "template_type": "generic",
          "elements": bodyObj['providers'].map(provider => ({
              "title": provider.name,
              "image_url": provider.coverImage.toString(),
              "subtitle": provider.location.textLoc,
              "buttons": [{
                  "type": "postback",
                  "payload": config.VIEW_SERVICES,
                  "title": "Select"
              }]
          }))
        }
      }
    }