更改/重命名对象或交换内容或名称

时间:2018-05-11 17:46:39

标签: javascript object rename

我有以下代码,想要更改名称或switsch值,但我不知道它是如何工作的并且很容易

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));`

我想将firstname更改为lastname,将lastname更改为firstname。

1 个答案:

答案 0 :(得分:0)

要达到预期效果,请使用以下使用地图

的选项



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




代码示例 - https://codepen.io/nagasai/pen/rvvpwN?editors=1010

选项2:

使用forEach来实现预期的结果,唯一的区别是forEach()只返回什么,但map()返回一个全新的数组。
有关详细信息,请查看此链接 - 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)