[英]how to add object in nested array of objects without mutating original source
[英]How to change an object Key without mutating original array
我有一个对象数组-我想在不改变原始数组的情况下将对象键之一更改为其他对象。 解决此问题的最佳方法是什么?
我了解我可以使用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" }
]
您可以map
参数数组,并使用散布运算符将其复制到其中的每个对象。 对于每个新对象,如果它包含我们要删除的键,则将值复制到新键,然后delete
旧键。
const books = [ {title: "To Kill a Mockingbird", writtenBy: "Harper Lee"}, {title: "A Clockwork Orange", author: "Anthony Burgess"}, {title: "The Elephant Tree", writtenBy: "RD 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);
数组辅助对象(例如map,filter,reduce等)不会突变原始数组,而是返回新数组。 Map接收一个函数作为参数(回调)。 映射迭代数组,在每个元素中应用回调。
const books = [ {title: "To Kill a Mockingbird", writtenBy: "Harper Lee"}, {title: "A Clockwork Orange", author: "Anthony Burgess"}, {title: "The Elephant Tree", writtenBy: "RD Ronald"} ]; //Function to use as a callback on map function changeKey(current) { if(current.author) return { title: current.title, writtenBy: current.author }; return current; } //Creating new array applying changeKey in every element thanks to map const newBooks = books.map(changeKey); console.log(newBooks);
以下内容不会使books
数组发生变化。
const books = [ { title: "To Kill a Mockingbird", writtenBy: "Harper Lee" }, { title: "A Clockwork Orange", author: "Anthony Burgess" }, { title: "The Elephant Tree", writtenBy: "RD Ronald" } ]; const renamedBooks = books.map(book => { if (book.author) { return { title: book.title, writtenBy: book.author }; } return book; }); console.info(renamedBooks);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.