假设我有一个名为data
的对象:
{
first: 'Zaaac',
last: 'Ezzell',
title: 'Mrs',
mail: 'oezzell0@reddit.com',
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'
}
我希望根据映射对象字段
重命名每个键:
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'
}
}
例如,其思想是在对象A中出现first
键的任何地方,将其重命名为first_name
。 在出现last
的地方,将其重命名为last_name
,依此类推。
我尝试了以下操作:
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);
});
但是,结果对象中的键保持不变。
预期产出:
{
first_name: 'Zaaac',
last_name: 'Ezzell',
title: 'Mrs',
email: 'oezzell0@reddit.com',
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'
}
您可以获取object的条目,然后获取fromEntries onced mapped:
null
var mapObj= { 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' }};
var obj={ first: 'Zaaac', last: 'Ezzell', title: 'Mrs', mail: 'oezzell0@reddit.com', 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' };
var result = Object.fromEntries(Object.entries(obj).map(([k,v])=>([mapObj.fieldValue[k] == "null" ? k : mapObj.fieldValue[k] ,v])));
console.log(result);