-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?

0

3 Answers 3

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; }

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

thank you so much. I was having difficulties to clone the array. nice solution @coolgoose
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);

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.