You need to enable JavaScript to run this app. 如何将camel case转sentence case函数应用于对象数组批量转换属性名
优惠活动
大模型
产品
解决方案
定价
更多

如何将camel case转sentence case函数应用于对象数组批量转换属性名

问题描述

现有如下结构的对象数组:

myData = [
  { firstName: 'john', lastName: 'y', hairColor: 'black' },
  { firstName: 'mike', lastName: 'x', hairColor: 'green' },
  { firstName: 'alex', lastName: 'z', hairColor: 'brown' }
];

需要将其转换为如下结构:

myData = [
  { 'First name': 'john', 'Last name': 'y', 'Hair color': 'black' },
  { 'First name': 'mike', 'Last name': 'x', 'Hair color': 'green' },
  { 'First name': 'alex', 'Last name': 'z', 'Hair color': 'brown' }
];

核心需求是将对象的属性名从camel case转换为sentence case,例如将 firstName 转换为 First name。
已编写用于实现单个字符串转换的函数:

function replaceIt(text) {
  const result = text.replace(/([A-Z])/g, " $1");
  const finalResult = result.charAt(0).toUpperCase() + result.slice(1);
  return finalResult;
}

不清楚如何将该函数应用到上述对象数组中,曾考虑使用类似 myData.forEach(a => ... ); 的写法,但未完成实现。

解决方案

修正现有转换函数

原函数处理 firstName 时会输出 First Name(第二个单词首字母保留大写),不符合需求的 First name 格式,需调整正则替换逻辑,将提取到的大写字母转为小写:

function replaceIt(text) {
  // 匹配驼峰命名中的大写字母,替换为空格+小写形式
  const spacedText = text.replace(/([A-Z])/g, match => ` ${match.toLowerCase()}`);
  // 仅将字符串首字母大写,符合sentence case要求
  return spacedText.charAt(0).toUpperCase() + spacedText.slice(1);
}

数组遍历实现转换

推荐使用 map 生成新数组,不修改原始数据,避免副作用:

// 生成转换后的新数组,如需覆盖原数组可直接赋值给myData
const convertedData = myData.map(item => 
  Object.fromEntries(
    // 遍历当前对象的所有键值对,对键应用转换函数
    Object.entries(item).map(([key, value]) => [replaceIt(key), value])
  )
);

如果需要直接修改原数组,可使用你提到的 forEach 实现:

myData.forEach((item, index, arr) => {
  const newItem = {};
  // 遍历当前对象的所有自有属性,避免遍历原型链属性
  for (const key in item) {
    if (item.hasOwnProperty(key)) {
      newItem[replaceIt(key)] = item[key];
    }
  }
  // 替换原数组中的旧对象
  arr[index] = newItem;
});

注意事项

  • 转换后的属性名包含空格,后续引用时需要添加引号,例如 convertedData[0]['First name']。
  • 使用 Object.entries 配合 Object.fromEntries 的写法比 for...in 更简洁安全,不会遍历对象原型链上的非自有属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.02 09:27:03