簡體   English   中英

如何在不更改原始數組的情況下更改對象Key

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM