数组修改对象多个key值
function changeObjectKeys(obj, keyMapping) {
const newObj = { ...obj };
for (const oldKey in keyMapping) {
if (newObj.hasOwnProperty(oldKey)) {
const newKey = keyMapping[oldKey];
newObj[newKey] = newObj[oldKey];
delete newObj[oldKey];
}
}
return newObj;
}
function changeArrayObjectsKeys(array, keyMapping) {
return array.map((item) => changeObjectKeys(item, keyMapping));
}
const originalArray = [
{ name: 'John Doe', age: 30, city: 'New York' },
{ name: 'Jane Smith', age: 28, city: 'Los Angeles' },
];
const keyMapping = {
city: 'location',
age: 'yearsOld',
};
const newArray = changeArrayObjectsKeys(originalArray, keyMapping);
console.log(newArray);