首页 > 解决方案 > 更改数组上的一些对象键并保持顺序

问题描述

我正在尝试按顺序重命名数组中一系列对象的某些属性,但我只想将名称更改为某些属性,而不必重建整个对象以保持相同的顺序。

const data = [
  {
    prop1: 'Change key but keep position',
    second: 'Keep same key name and position',
    prop3: 'Change key but keep position',
    fourth: 'Keep same key name and position',
  }
]

const res = data.map(({prop1, prop3, ...obj}) => ({
  first: prop1,
  third: prop3,
  ...obj,
}))


console.log(res)
.as-console-wrapper { max-height: 100% !important; top: 0; }

期望的输出

[
 {
   first: 'Change key but keep position',
   second: 'Keep same key name and position',
   third: 'Change key but keep position',
   fourth: 'Keep same key name and position'
 }
]

标签: javascriptarraysobjectecmascript-6

解决方案


也许是这样的:

const data = [
  {
    prop1: 'Change key but keep position',
    second: 'Keep same key name and position',
    prop3: 'Change key but keep position',
    fourth: 'Keep same key name and position',
  }
];

const renameMap = { prop1: 'first', prop3: 'third'};

const res = data.map(
  obj => Object.fromEntries(Object.entries(obj).map(
    ([key, value]) => [renameMap[key] ?? key, value]
  ))
);

console.log(res);


推荐阅读