重构一个对象的拾取字段并将其分配给其他对象

时间:2018-02-16 10:37:36

标签: javascript ecmascript-6 ecmascript-7

如果我有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

1 个答案:

答案 0 :(得分:-2)

// 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) // { ... }