【发布时间】:2019-10-26 09:31:20
【问题描述】:
我有一个对象数组 - 我想在不改变原始数组的情况下将其中一个对象键更改为其他值。解决这个问题的最佳方法是什么?
我知道我可以使用 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" }
]
【问题讨论】:
-
不确定我是否理解这个问题:
books是一个 const 数组与这个问题 100% 无关,因为您想更改其中一个包含对象中的字段,所以......只需更改它?let e = books.find(......); e.writtenBy = e.author; delete e.author;完成了吗? (使用Array.find() 函数,如果您需要在每个元素上运行它,forEach应该可以避免使用find())
标签: javascript arrays javascript-objects