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

JavaScript中如何实现数组对象的键名替换?

实现对象数组的键名映射替换

可以通过数组的map和reduce方法组合实现,步骤如下:

1. 修正笔误(重要)

注意原数组myObject1中的键名拼写错误:adddress多了一个字母d,需要修正为address才能和映射数组匹配,否则无法正确取值。

2. 具体实现代码

// 修正后的原对象数组
var myObject1 = [
   {name: "value1", address: "545454545445"},
   {name: "value2", address: "323233223"},
   {name: "value3", address: "33232"},
];

// 键名映射关系
const myObject = [
   ['aa', 'name'],
   ['bb', 'address']
];

// 执行转换
const transformedArray = myObject1.map(item => 
  myObject.reduce((newItem, [newKey, oldKey]) => {
    newItem[newKey] = item[oldKey];
    return newItem;
  }, {})
);

console.log(transformedArray);

代码解释

  • myObject1.map(item => ...):遍历原数组的每个对象,对每个对象进行转换。
  • myObject.reduce(...):遍历映射数组,每次迭代将原对象中oldKey对应的值,赋值给新对象的newKey,最终生成转换后的单个对象。
  • 最终得到的transformedArray就是你需要的目标数组。

另一种实现方式(基于映射对象)

如果需要更灵活地处理键名,也可以先把映射数组转换成键值对对象,再遍历原对象的键:

const keyMapping = Object.fromEntries(myObject.map(([newKey, oldKey]) => [oldKey, newKey]));

const transformedArray = myObject1.map(item => {
  const newItem = {};
  for (const oldKey in item) {
    const newKey = keyMapping[oldKey];
    if (newKey) {
      newItem[newKey] = item[oldKey];
    }
  }
  return newItem;
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 16:07:09