简体   繁体   中英

Mapping req.body properties to object key

Right now when I want to add an object to the database I do the following:

return BSRequest.create({
            salon_name: req.body.salon_name,
            salon_type: req.body.salon_type,
            employees: req.body.employees,
            postcode: req.body.postcode,
            city: req.body.city,
            website: req.body.website,
            first_name: req.body.first_name,
            last_name: req.body.last_name,
            email: req.body.email,
            phone_number: req.body.phone_number
        })
            .then(bsRequest => res.status(201).send(bsRequest))
            .catch(error => res.status(400).send(error));

Is there a way in Javascript/Node to automatically get the properties of req.body so that these can be mapped to the key of the object? Or some other way that I can simplify it and have less code.

I'm using the sequelize ORM.

I can see you are using body-parser or some other kind of request parser already (OBVIOUSLY) so you can just write a one-liner utility for doing this

## req.body = {a: 1, b:2, c:3, d:4}
let targetObj = {}
let keysYouWant = ['key1', 'key2']
Object.keys(req.body).forEach(key => { if (keysYouWant.includes(key)) targetObj[key] = req.body[key] })

But IF req.body has same keys as what you want in the targetObject then you can just do this

return BSRequest.create(req.body)
    .then((bsRequest) => { ... })
    .catch((error) => { ... })

if req.body and your database db model keys are same you can just write

return BSRequest.create(req.body).then(bsRequest => res.status(201).send(bsRequest)) .catch(error => res.status(400).send(error));

Comment: I'll not recommend that you directly store values in req.body to the database. Please do include type-check for values you get from frontend before saving them to the database. You can do that by making some modification in Akshay's answer.

Yes we have es6 spread feature to do this.Kindly check this link

Note: All values inside req.body will be passed

return BSRequest.create({...req.body}).then(bsRequest => res.status(201).send(bsRequest)).catch(error => res.status(400).send(error));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM