0

I have the following code and want to change the names or to switsch the value, but i have no idea how it can work and is easy

var employees = [{firstName: "Richter", lastName: "Johnas"},


{firstName: "Leibig", lastName: "Linda"},
{firstName: "Schneider", lastName: "Mariane"},
];
console.log("\n> Should display [{firstName: 'Johnas', lastName: 'Richter'}, {firstName: 'Linda', lastName: 'Leibig'}, {firstName: 'Mariane', lastName: 'Schneider'}]");
console.log(revertFirstNamesAndLastNames(employees));`

And i want to change the firstname to lastname and lastname to firstname.

TR54296
  • 17
  • 2
  • 9

1 Answers1

0

To achieve expected result, use below option of using map

var employees = [{firstName: "Richter", lastName: "Johnas"},


{firstName: "Leibig", lastName: "Linda"},
{firstName: "Schneider", lastName: "Mariane"},
];

employees.map((v,i)=>{
  let fname = v.firstName
  v.firstName = v.lastName
  v.lastName = fname
})
console.log(employees);

code sample - https://codepen.io/nagasai/pen/rvvpwN?editors=1010

Option 2:

Use forEach to achieve expected result and the only difference is that forEach() just return nothing but map() returns an entirely new Array. 
For more details, check this link - JavaScript: Difference between .forEach() and .map()

var employees = [{firstName: "Richter", lastName: "Johnas"},


{firstName: "Leibig", lastName: "Linda"},
{firstName: "Schneider", lastName: "Mariane"},
];

employees.forEach((v)=>{
  let fname = v.firstName
  v.firstName = v.lastName
  v.lastName = fname
})
console.log(employees)
Naga Sai A
  • 10,771
  • 1
  • 21
  • 40