迭代req.body来反对

时间:2017-09-01 18:01:45

标签: javascript node.js

我想在插入数据库之前将数据从req.body映射到对象

//object
var user = {
  name : "",
  age  : "",
  address : ""
}

router.route('/insertuser').post(function (req, res) {
    //iterate req.body values to matching user object value
});

是否可以迭代或缓冲req.body以匹配给定对象的值?谢谢你

3 个答案:

答案 0 :(得分:2)

如果你要做的是创建一个与user对象具有相同属性的新对象,但从req.body获取值,那么你可以这样做:

//object
var user = {
  name : "",
  age  : "",
  address : ""
}
router.route('/insertuser').post(function (req, res) {
    let newObj = {};
    Object.keys(user).forEach(function(prop) {
        newObj[prop] = req.body[prop];
    });
    // newObj is populated with name, age and address properties from req.body
});

答案 1 :(得分:0)

如果你正在运行一个相当新版本的nodejs,你可以这样做:

var {name, age, address} = req.body
var user = {name, age, address}

答案 2 :(得分:0)

我这样做:

//object
var userObject = {
  name : "",
  age  : "",
  address : ""
}

router.route('/insertuser').post(function (req, res) {
    newObject = {}
    Object.keys(userObject).map(function(key, index) {
        newObject[key] = req.body[key] 
    });

    // Then save the userObject to the database. 
});