Node.js中如何在forEach循环内存储对象键值对并传给Dialogflow机器人
解决方案
核心问题是forEach没有返回值,你在forEach内部执行return不会返回拼接结果,只需要在外层定义变量累计拼接内容即可,具体实现如下:
实现步骤
- 提前初始化空字符串变量作为最终回复文本
- 遍历酒店数组时直接往上述变量追加你需要的格式内容,不要在
forEach中写return逻辑 - 遍历完成后直接把完整变量传入
df.setResponseText()即可
代码示例
// 假设从数据库拿到的酒店数组为 hotelList const hotelList = [ { hotelname: "三亚海景度假酒店", city: "三亚", price: 688 }, { hotelname: "成都宽窄巷子亚朵酒店", city: "成都", price: 379 } ] // 初始化回复开头 let responseText = "为你查询到以下符合要求的酒店:\n\n" // 遍历拼接内容 hotelList.forEach((hotel, index) => { // 追加序号 responseText += `${index + 1}. \n` // 按要求拼接指定字段 responseText += `hotelname: ${hotel.hotelname}\n` responseText += `city: ${hotel.city}\n` responseText += `price: ${hotel.price}\n\n` }) // 返回给Dialogflow df.setResponseText(responseText)
如果需要动态适配字段,不用手动写死三个字段,可以用以下写法:
hotelList.forEach((hotel, index) => { responseText += `${index + 1}. \n` Object.keys(hotel).forEach(key => { responseText += `${key}: ${hotel[key]}\n` }) responseText += "\n" })
内容的提问来源于stack exchange,提问作者lakshmi
相关产品推荐
相关产品推荐

