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

如何在ReactJS中从复杂响应对象提取所有message字段?

在React中提取聊天响应里的所有message字段

我在ReactJS中通过dispatch调用fetchChats函数,获取到一个包含聊天数据的复杂数组响应对象,需要从中筛选提取所有的message字段,对此感到困惑。相关代码及响应结构如下:

调用代码

function showchat() {
  dispatch(fetchChats())
    .then((res) => {
      document.write(JSON.stringify(res));
    })
    .catch((err) => console.log(err));
}

fetchChats返回的响应结构

[
  {
    "id": 13,
    "type": "dual",
    "createdAt": "2022-11-01T18:42:08.487Z",
    "updatedAt": "2022-11-01T18:42:08.487Z",
    "ChatUser": {
      "chatId": 13,
      "userId": 72,
      "createdAt": "2022-11-01T18:42:08.499Z",
      "updatedAt": "2022-11-01T18:42:08.499Z"
    },
    "Users": [
      {
        "avtar": "http://127.0.0.1:3000/male.svg",
        "id": 71,
        "firstName": "dhruv",
        "lastName": "parmar",
        "email": "dhruvdp.js@gmail.com",
        "password": "$2b$10$VYQdhqz2ig3NP/8tbJtGHu9kWuNsym4oFobpdy9QLuTJPzQSBq0TG",
        "gender": "male",
        "createdAt": "2022-11-01",
        "updatedAt": "2022-11-01",
        "ChatUser": {
          "chatId": 13,
          "userId": 71,
          "createdAt": "2022-11-01T18:42:08.499Z",
          "updatedAt": "2022-11-01T18:42:08.499Z"
        },
        "status": "offline"
      }
    ],
    "Messages": [
      {
        "message": "Bhai kaisa hai?",
        "id": 13,
        "type": "text",
        "chatId": 13,
        "fromuserId": 71,
        "createdAt": "2022-11-01T18:42:08.505Z",
        "updatedAt": "2022-11-01T18:42:08.505Z",
        "User": {
          "avtar": "http://127.0.0.1:3000/male.svg",
          "id": 71,
          "firstName": "dhruv",
          "lastName": "parmar",
          "email": "dhruvdp.js@gmail.com",
          "password": "$2b$10$VYQdhqz2ig3NP/8tbJtGHu9kWuNsym4oFobpdy9QLuTJPzQSBq0TG",
          "gender": "male",
          "createdAt": "2022-11-01",
          "updatedAt": "2022-11-01"
        }
      },
      {
        "message": "Badiya bhai tu bata",
        "id": 14,
        "type": "text",
        "chatId": 13,
        "fromuserId": 72,
        "createdAt": "2022-11-01T18:42:08.505Z",
        "updatedAt": "2022-11-01T18:42:08.505Z",
        "User": {
          "avtar": "http://127.0.0.1:3000/male.svg",
          "id": 72,
          "firstName": "Harshit",
          "lastName": "rajpal",
          "email": "harshit@gmail.com",
          "password": "$2b$10$pGZ./D2axPY4WE.raJW0eOSIX11RluimkIMQ7bDwWgYBsyzhrBFtu",
          "gender": "male",
          "createdAt": "2022-11-01",
          "updatedAt": "2022-11-01"
        }
      },
      {
        "message": "Bass apki kripa",
        "id": 15,
        "type": "text",
        "chatId": 13,
        "fromuserId": 71,
        "createdAt": "2022-11-01T18:42:08.505Z",
        "updatedAt": "2022-11-01T18:42:08.505Z",
        "User": {
          "avtar": "http://127.0.0.1:3000/male.svg",
          "id": 71,
          "firstName": "dhruv",
          "lastName": "parmar",
          "email": "dhruvdp.js@gmail.com",
          "password": "$2b$10$VYQdhqz2ig3NP/8tbJtGHu9kWuNsym4oFobpdy9QLuTJPzQSBq0TG",
          "gender": "male",
          "createdAt": "2022-11-01",
          "updatedAt": "2022-11-01"
        }
      }
    ]
  }
]

未转字符串时的res显示效果:
未转字符串的res显示效果


解决方案

响应是一个数组,每个元素对应一个聊天会话,会话里的Messages数组包含了所有消息对象,每个消息对象的message字段就是你要提取的内容。可以用数组的flatMap和map方法组合提取:

修改后的代码

function showchat() {
  dispatch(fetchChats())
    .then((res) => {
      // 提取所有message字段到一维数组
      const allMessages = res.flatMap(chat => chat.Messages.map(msg => msg.message));
      console.log(allMessages);
      // 若要在页面展示,可将结果存入state(示例)
      // setAllMessages(allMessages);
    })
    .catch((err) => console.log(err));
}

代码说明

  • flatMap:遍历响应数组中的每个聊天会话,取出会话的Messages数组并展开,避免生成嵌套数组
  • map:从每个消息对象中提取message字段值

安全处理(可选)

如果存在会话没有Messages字段或Messages为空的情况,可以添加判断避免报错:

const allMessages = res.flatMap(chat => {
  // 确保chat有Messages属性且为数组,否则返回空数组
  return chat.Messages?.map(msg => msg.message) || [];
});

内容的提问来源于stack exchange,提问作者dhruv parmar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 03:55:29