Javascript nodejs中表单数据的提取

Javascript nodejs中表单数据的提取,javascript,html,node.js,Javascript,Html,Node.js,我在一封html电子邮件中有一个表单,可以发布到/查看 提交表单中的数据来自表单中的输入字段 我使用req.body获取表单数据,如下所示: { customer_id: '52fa6ded48e3a50000000007', shop_name: 'sage-arts', 'product-226039457-emotion': 'sucks', 'product-226039457-comment': '1', 'product-222924077-emotion'

我在一封html电子邮件中有一个表单,可以发布到/查看 提交表单中的数据来自表单中的输入字段

我使用req.body获取表单数据,如下所示:

{ 
  customer_id: '52fa6ded48e3a50000000007',
  shop_name: 'sage-arts',

  'product-226039457-emotion': 'sucks',
  'product-226039457-comment': '1',

  'product-222924077-emotion': 'rocks',
  'product-222924077-comment': '12',

  'submit-review': 'Submit your review'
}
var shop = form['shop_name'];
var customer = form['customer_id'];
product-…-emotion
product-…-comment
对可以是一对或多对,在上述情况下为2。 无论有多少对,我都需要提取这些对并对它们进行处理

我知道
customer\u id
shop\u name
总是一样的,所以我得到如下结果:

{ 
  customer_id: '52fa6ded48e3a50000000007',
  shop_name: 'sage-arts',

  'product-226039457-emotion': 'sucks',
  'product-226039457-comment': '1',

  'product-222924077-emotion': 'rocks',
  'product-222924077-comment': '12',

  'submit-review': 'Submit your review'
}
var shop = form['shop_name'];
var customer = form['customer_id'];
但其余的都有不可预测的关键。我试过了

form[2];
但是我得到了
未定义的


在不事先知道密钥的情况下提取所需数据的好方法是什么?

您必须迭代对象并进行一些匹配:

for(var field in req.body){
    if(field.match(/^product-\d+-emotion$/)){
        // do something with req.body[field]
    }
    if(field.match(/^product-\d+-comment$/)){
        // do something with req.body[field]
    }
}
我猜转换这些数据会很有帮助,这样您就有了一个由产品ID设置关键帧的对象。你可以这样做:

var products = {};
for(var field in req.body){
    var m;
    m = field.match(/^product-(\d+)-emotion$/);
    if(m) {
        var id = m[1];
        if(!products[id]) products[id] = {};
        products[id].emotion = req.body[field];
        continue;
    }
    m = field.match(/^product-(\d+)-comment$/);
    if(m) {
        var id = m[1];
        if(!products[id]) products[id] = {};
        products[id].comment = req.body[field];
        continue;
    }
}
如果字段的格式始终为
product-99999-something
,则可以使其更加通用:

var products = {};
for(var field in req.body){
    var m;
    m = field.match(/^product-(\d+)-(\w+)$/);
    if(m) {
        var id = m[1];
        var prop = m[2];
        if(!products[id]) products[id] = {};
        products[id][prop] = req.body[field];
    }
}

只需在对象上循环并测试键是否与您的
产品-\d+-(情感|评论)
模式匹配?您可以通过对象在表单对象中获得属性列表。键(表单)谢谢各位,我现在已经开始工作了。我尝试了这两种方法Object.keys(表单)给了我一个所有键的数组,我也尝试了(表单中的键),并且能够迭代所有键。再次感谢