Looking for an efficient solution to replace property keys in an array of objects using a map? Here's an example scenario:
// Consider an array of objects:
var records = [
{"Id": "0035w000036m j7oAAA", "Business Phone": "(212) 842-5501"},
{"Id": "0035w000036mj7oXXX", "Business Phone": "(212) 842-7777"}
];
// Map for property key replacement:
var colHeaderToFieldApiName = {"Business Phone": "Phone"};
// Expected output:
var result = [
{"Id": "0035w000036mj7oAAA", "Phone": "(212) 842-5501"},
{"Id": "0035w000036mj7oXXX", "Phone": "(212) 842-7777"}
];
I've written a solution that functions correctly, but I'm open to suggestions for improvement. Here's what it currently looks like:
records.forEach(function(obj) {
for (const prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
const fieldApiName = colHeaderToFieldApiName[prop];
if (fieldApiName) {
obj[fieldApiName] = obj[prop];
delete obj[prop];
}
}
}
});