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

如何使用_.mapKeys处理对象数组,将text键改为label?

使用 Lodash 的 _.mapKeys 重命名对象键

没问题,用 Lodash 的 _.mapKeys 可以轻松实现这个需求——我们只需要结合数组遍历,对每个对象单独处理键的映射即可,具体代码如下:

// 先引入 Lodash(如果是浏览器环境可能已经全局可用)
const _ = require('lodash');

// 你的原始数组
const originalColors = [ 
  {id: 0, text: "blue"}, 
  {id: 1, text: "green"}, 
  {id: 2, text: "orange"}, 
  {id: 3, text: "yellow"} 
];

// 转换数组:遍历每个对象,用 _.mapKeys 重命名键
const transformedColors = originalColors.map(color => 
  _.mapKeys(color, (value, key) => {
    // 判断键名,text 替换为 label,其他键保持不变
    return key === 'text' ? 'label' : key;
  })
);

console.log(transformedColors);
// 输出结果:
// [ {id: 0, label: "blue"}, {id: 1, label: "green"}, {id: 2, label: "orange"}, {id: 3, label: "yellow"} ]

原理说明

  • _.mapKeys 的作用是遍历对象的所有键,返回一个新对象(不会修改原对象),回调函数的第二个参数就是当前遍历的键名,我们在这里做判断替换即可。
  • 外层的 Array.map() 是原生数组方法,用来遍历整个数组,对每个对象应用 _.mapKeys 的转换逻辑。如果你更习惯用 Lodash 的遍历方法,也可以换成 _.map,效果完全一致:
// 用 Lodash 的 _.map 代替原生 map
const transformedColors = _.map(originalColors, color => 
  _.mapKeys(color, (value, key) => key === 'text' ? 'label' : key)
);

这种方式是纯函数式的处理,不会污染原数组和原对象,非常适合这类数据转换场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:51:29