如何遍历bodyObj生成Facebook Messenger机器人通用模板元素?
Got it! Here's how you can dynamically generate all the elements in your Facebook Messenger generic template by looping through your bodyObj['providers'] array instead of hardcoding them:
Refactored Code
// Generate elements dynamically from all providers const templateElements = 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" }] })); const campaigns = { "attachment": { "type": "template", "payload": { "template_type": "generic", "elements": templateElements // Use the dynamically generated array here } } };
How It Works
- We use
Array.map()to iterate over every provider inbodyObj['providers']and convert each one into the exact element structure Messenger's generic template expects. - This approach automatically scales: whether you have 2 providers or 20, all will be added to the template without any manual code changes.
- If
bodyObj['providers']is empty, theelementsarray will be empty too—Messenger handles this gracefully by not displaying any template items (you might want to add a fallback message for this case if needed).
内容的提问来源于stack exchange,提问作者mikayiri
相关产品推荐
相关产品推荐

