renameKeys [重命名键]
用提供的值替换多个对象键的名称。
使用 Object.keys()
结合 Array.prototype.reduce()
和传播操作员 (...
) 获取对象的钥匙并根据 keysMap
.
const renameKeys = (keysMap, obj) =>
Object.keys(obj).reduce(
(acc, key) => ({
...acc,
...{ [keysMap[key] || key]: obj[key] },
}),
{}
);
const obj = { name: "Bobo", job: "Front-End Master", shoeSize: 100 };
renameKeys({ name: "firstName", job: "passion" }, obj); // { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 }