如何在不更改原始数组的情况下更改对象Key

时间:2019-06-11 22:41:59

标签: javascript arrays javascript-objects

我有一个对象数组-我想在不更改原始数组的情况下将其中一个对象键更改为其他对象。解决此问题的最佳方法是什么?

我知道我可以使用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" } 
]

3 个答案:

答案 0 :(得分:0)

您可以map使用扩展运算符来delete并复制其中的每个对象。对于每个新对象,如果它包含我们要删除的键,则将值复制到新键,并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);旧键。

json

答案 1 :(得分:-1)

诸如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: "R.D. 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);

答案 2 :(得分:-2)

以下内容不会使books数组发生突变。

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 renamedBooks = books.map(book => {
  if (book.author) {
    return {
      title: book.title,
      writtenBy: book.author
    };
  }

  return book;
});

console.info(renamedBooks);