【问题标题】:Refactoring picking fields from one object and assigning them to other [duplicate]重构从一个对象中挑选字段并将它们分配给其他[重复]
【发布时间】:2018-02-16 10:37:35
【问题描述】:

如果我有 book 具有以下结构的对象

{title: string, author: string, genre: string, read: boolean}

我有 req.body,它包含来自 book 对象的所有字段以及其他一些字段

有没有办法将下面的代码重构得更简洁?

book.title = req.body.title
book.author = req.body.author
book.genre = req.body.genre
book.read = req.body.read

【问题讨论】:

  • 您可以尝试Object.assign 将所有属性从一个对象复制到另一个对象。
  • 你为什么不首先在 req.body 中发送书,即 req.body.book

标签: javascript ecmascript-6 ecmascript-2016


【解决方案1】:
// req.body = { otherThing: 'something', title: 'ok', author: 'aut', genre: 'scifi', read: false, foo: 'bar', bar: 'foo' }

const { title, author, genre, read } = req.body
const book = { title, author, genre, read }

console.log(book) // { ... }

【讨论】:

  • req.body 比书籍对象的所有属性都多,所以这是错误的答案。
  • 查看使用解构赋值的更新。
猜你喜欢
  • 2020-10-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-26
  • 2014-07-31
相关资源
最近更新 更多