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

如何基于键名子串将对象转换为对象数组,适配React函数式组件状态存储

实现方案

步骤1:实现转换辅助函数

核心逻辑是通过正则拆分键名的用户编号和属性字段,按编号分组后转为数组,同时对齐示例要求的属性名大小写:

const transformUserObject = (rawObj) => {
  const userGroups = {};
  // 遍历原始对象所有键值对
  Object.entries(rawObj).forEach(([key, value]) => {
    // 正则匹配提取用户编号和属性名
    const match = key.match(/^User (\d+) (.*)$/);
    if (!match) return; // 跳过不符合命名规则的异常键
    const userId = match[1];
    let attrName = match[2];
    // 处理属性名大小写,和示例输出对齐
    if (attrName === 'nombre') attrName = 'Nombre';
    // 初始化对应编号的用户对象
    if (!userGroups[userId]) userGroups[userId] = {};
    userGroups[userId][attrName] = value;
  });
  // 分组对象转数组,顺序和用户编号从小到大一致
  return Object.values(userGroups);
};

步骤2:在React函数式组件中存入state

你可以在拿到原始对象的时机(接口请求完成、props更新、用户操作触发等)调用转换函数,再将结果存入state,示例代码如下:

import { useState, useEffect } from 'react';

const UserList = () => {
  const [userArray, setUserArray] = useState([]);

  // 示例:组件初始化时处理原始对象并存入state
  useEffect(() => {
    // 你的原始对象
    const rawUserObject = {
      "User 1 Fecha de Nacimiento": "02/05/2000",
      "User 1 Porcentage": 25,
      "User 1 Primer Apellido": "Gonzalez",
      "User 1 Segundo Apellido": "Perez",
      "User 1 Sexo": "H",
      "User 1 nombre": "Manuel",
      "User 2 Fecha de Nacimiento": "02/05/2000",
      "User 2 Porcentage": 25,
      "User 2 Primer Apellido": "Diaz",
      "User 2 Segundo Apellido": "Rodriguez",
      "User 2 Sexo": "M",
      "User 2 nombre": "Pepa",
    };
    // 调用转换函数
    const formattedResult = transformUserObject(rawUserObject);
    // 存入state
    setUserArray(formattedResult);
  }, []);

  // 后续可直接使用userArray渲染页面
  return (
    <div>
      {userArray.map((user, idx) => (
        <div key={idx}>
          <p>用户姓名:{user.Nombre} {user['Primer Apellido']}</p>
          <p>出生日期:{user['Fecha de Nacimiento']}</p>
        </div>
      ))}
    </div>
  )
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 01:51:03