我有一个对象数组 - 我想在不改变原始数组的情况下将其中一个对象键更改为其他键。解决这个问题的最佳方法是什么?
我知道我可以使用 Map 方法,但不确定它是如何工作的。谢谢
const books = [
{ title: "To Kill a Mockingbird", writtenBy: "Harper Lee" },
{ title: "A Clockwork Orange", author: "Anthony Burgess" },
{ title: "The Elephant Tree", writtenBy: "R.D. Ronald" }
]
function changeKey(arr, keyChange, newKey) {
}
// i want to return so the KEY keyChange(author) is changed to newKey(writtenBy)
[
{ title: "To Kill a Mockingbird", writtenBy: "Harper Lee" },
{ title: "A Clockwork Orange", writtenBy: "Anthony Burgess" },
{ title: "The Elephant Tree", writtenBy: "R.D. Ronald" }
]
最佳答案
您可以映射
参数数组并使用扩展运算符浅层复制其中的每个对象。对于每个新对象,如果它包含我们要删除的键,则将值复制到新键并删除
旧键。
const books = [ {title: "To Kill a Mockingbird", writtenBy: "Harper Lee"}, {title: "A Clockwork Orange", author: "Anthony Burgess"}, {title: "The Elephant Tree", writtenBy: "R.D. Ronald"} ];
const changeKey = (arr, keyChange, newKey) =>
arr.map(e => {
const o = {...e};
if (keyChange in o) {
o[newKey] = o[keyChange];
delete o[keyChange];
}
return o;
})
;
console.log(changeKey(books, "author", "writtenBy"));
console.log(books);
关于javascript - 如何在不改变原始数组的情况下更改对象键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56552524/