You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何遍历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 in bodyObj['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, the elements array 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:05:40