javascript - 更改数组上的一些对象键并保持顺序
问题描述
我正在尝试按顺序重命名数组中一系列对象的某些属性,但我只想将名称更改为某些属性,而不必重建整个对象以保持相同的顺序。
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'
}
]
解决方案
也许是这样的:
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);
推荐阅读
- typescript - ERROR 错误 TS2365:运算符 '<=' 不能应用于类型 'string' 和 'number'
- android-espresso - 安卓。Espresso:如何检查 TextView 的大写?
- c# - Unity 单元测试 - 检查带有参数的函数调用是否引发异常
- android - ConstraintLayout:文本展开时保持在父级中的复合 ImageView
- java - 将“while”循环转换为“for”和“do while”
- ios - Twilio caller name on receive programmable voice call in ios application
- c++ - 检查数组的2个元素
- php - 无法在弹出式联系表单中输入内容
- java - 无法构建我的应用
- java - 在java中添加两个char数据类型