Suppose I have an object called data
:
{
first: 'Zaaac',
last: 'Ezzell',
title: 'Mrs',
mail: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83ece6f9f9e6efefb3c3f1e6e7e7eaf7ade0ecee">[email protected]</a>',
cellphone: '+444444',
phone_2: '6506679207',
address_2: 'Holmberg',
address_1: '34 Scott Center',
address_3: 'Iowa City',
address_4: 'Stephen',
address_5: 'Iowa',
country: 'United States',
zipcode: '52245'
}
I want to change each key based on a mapping object called fields
:
fields: {
fieldName: 'map',
fieldValue: {
first: 'first_name',
last: 'last_name',
title: 'null',
mail: 'email',
cellphone: 'cellphone',
phone_2: 'null',
address_1: 'address_line_1',
address_2: 'address_line_2',
address_3: 'null',
address_4: 'null',
address_5: 'null',
zipcode: 'null',
country: 'country'
}
}
For instance, whenever the key first
is found in Object A, it should be changed to first_name
. Similarly, replace last
with last_name
and so on.
I attempted the following:
await data.forEach((element) => {
Object.keys(element).forEach(function(key) {
console.log('Contact: ' + key + ': ' + element[key]);
Object.keys(fields['fieldValue']).forEach(function(mapKey) {
if (fields['fieldValue'][mapKey] !== 'null') {
key = fields['fieldValue'][mapKey];
console.log('LOG: KEY: ', key);
}
});
});
console.log('LOG: Element: ', element);
});
However, the keys in the resultant Object remain unchanged.
Expected result:
{
first_name: 'Zaaac',
last_name: 'Ezzell',
title: 'Mrs',
email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7a151f00001f16164a3a081f1e1e130e54191517">[email protected]</a>',
cellphone: '+444444',
phone_2: '6506679207',
address_line_2: 'Holmberg',
address_line_1: '34 Scott Center',
address_3: 'Iowa City',
address_4: 'Stephen',
address_5: 'Iowa',
country: 'United States',
zipcode: '52245'
}