循环访问 Facebook Messenger 机器人元素

Loop through facebook messengger bot elements

我有下面的代码

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"
                            }]
                        }
                        ]
                    }
                }
            }

但我想找到一种方法来循环遍历 bodyObj 对象并在 facebook Messenger bot 模板中显示每个元素的详细信息,而不是我上面所做的。 非常感谢您的帮助,提前致谢

只需在elements中使用map 属性:

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"
          }]
      }))
    }
  }
}