-1

I have two array. 1) userDetails, engToGerman

const userDetails= [
  {
    firstName: 'Michael Scott',
    lastName: 'Dunder Mufflin',
    designation: 'Regional Manager',
    show: 'The Office',
    responsibility: 'heart of the show'
  },
  {
    firstName: 'Michael Scott',
    lastName: 'Dunder Mufflin',
    designation: 'Regional Manager',
    show: 'The Office',
    responsibility: 'heart of the show'

  },
  {
    firstName: 'Michael Scott',
    lastName: 'Mufflin',
    designation: 'Regional Manager',
    show: 'The Office',
    responsibility: 'heart of the show'

  },
]

engToGerman = [ 
   firstName: 'name',
   lastName: 'vorname'
]

Now I would like to modify user details like below where I translate the first name and last name from engToGerman and want to delete the rest of the information.

So the new user detail will look like this:

const newUserDetails= [
  {
    name: 'Michael Scott',
    vorname: 'Dunder Mufflin',
  },
  {
    name: 'Michael Scott',
    vorname: 'Dunder Mufflin',

  },
  {
    name: 'Michael Scott',
    vorname: 'Mufflin',

  }
]

How can I achieve this without modifying the original array?

Kazi
  • 1,461
  • 3
  • 19
  • 47

3 Answers3

1

Easy version similar to the question / response here

let cloned = JSON.parse(JSON.stringify(userDetails));

Then you can do your normal array map or whatever else you need.

CoolGoose
  • 508
  • 1
  • 5
  • 16
  • thank you so much. I was having difficulties to clone the array. nice solution @coolgoose – Kazi Jun 23 '21 at 14:35
1

You can use array#map to map firstName and lastName.

const userDetails= [ { firstName: 'Michael Scott', lastName: 'Dunder Mufflin', designation: 'Regional Manager', show: 'The Office', responsibility: 'heart of the show' }, { firstName: 'Michael Scott', lastName: 'Dunder Mufflin', designation: 'Regional Manager', show: 'The Office', responsibility: 'heart of the show' }, { firstName: 'Michael Scott', lastName: 'Mufflin', designation: 'Regional Manager', show: 'The Office', responsibility: 'heart of the show' }, ],
    engToGerman = { firstName: 'name', lastName: 'vorname'},
    result = userDetails.map(o => ({ [engToGerman.firstName]: o.firstName, [engToGerman.lastName]: o.lastName }));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

here is the solution

const newUserDetails = [];

for(let item in userDetails){ //iterate through the entire array
  const obj = {
    name : userDetails[item].firstname,
    vorname: userDetails[item].lastname
  }
  newUserDetails.push(obj);

}
Ihtisham Tanveer
  • 338
  • 4
  • 15