0

Let's say I have an object named 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'
  }

I wish to rename each of the keys according to a mapping object, 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 example, the idea is that everywhere in Object A where the key of first occurs, rename it to first_name. Where last occurs, rename it to last_name and so on.

I have tried 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 resulting Object remain unchanged.

Expected output:

{
      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'
    }
Kuyashii
  • 360
  • 1
  • 4
  • 21

1 Answers1

1

You can take entries of object, then take fromEntries onced mapped:

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);
gorak
  • 5,233
  • 1
  • 7
  • 19