0

If I have book object with following structure

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

and I have the req.body that has all the fields from book object as well as few others.

Is there a way to refactor following code to more concise?

book.title = req.body.title
book.author = req.body.author
book.genre = req.body.genre
book.read = req.body.read
zmii
  • 3,268
  • 2
  • 29
  • 53
  • You can try [Object.assign](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) to copy all properties from one object to another. – xander Feb 16 '18 at 10:38
  • 1
    Why dont you send book in req.body at the first place i.e. req.body.book – Nikhil Aggarwal Feb 16 '18 at 10:38

1 Answers1

-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) // { ... }
senojoeht
  • 302
  • 1
  • 11