【问题标题】:How should I parse an array of objects in Node.js?我应该如何解析 Node.js 中的对象数组?
【发布时间】:2018-05-23 23:01:01
【问题描述】:

根据我的研究,通过 POST 方法传递对象数组的最佳方法是使用以下命名约定:

<!-- first student -->
<input type="text" name="students[][first]">
<input type="text" name="students[][last]">
<input type="text" name="students[][age]">

<!-- second student -->
<input type="text" name="students[][first]">
<input type="text" name="students[][last]">
<input type="text" name="students[][age]">

身体解析器设置:

var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: true}));

当我输入发布路线“req.body.students”时,我期待一个这样的对象数组:

[ { first: Fname1, last: Lname1, age: Age1} , { first: Fname2, last: Lname2, age: Age2}

相反,我的 console.log 显示我得到了这个:

[ { first : [Fname1 , Fname2], last : [Lname1, Lname2], age : [Age1, Age2] } ] 

它出了什么问题?干杯!

【问题讨论】:

    标签: html node.js express body-parser


    【解决方案1】:

    这就是the qa library 处理格式数据的简单方式。

    这不是我期望库的行为方式,它与 PHP(显而易见的灵感)处理数据的方式不同。所以你可能会认为这是一个错误和join in the discussion on this issue

    您可以通过对行使用显式索引来解决此问题:

    <!-- first student -->
    <input type="text" name="students[0][first]">
    <input type="text" name="students[0][last]">
    <input type="text" name="students[0][age]">
    
    <!-- second student -->
    <input type="text" name="students[1][first]">
    <input type="text" name="students[1][last]">
    <input type="text" name="students[1][age]">
    

    一个测试用例:

    var qs = require("qs");
    var data = "students[0][name]=alice&students[0][age]=11&students[1][name]=bob&students[1][age]=12";
    console.log(qs.parse(data));
    

    输出:

    { students: [ { name: 'alice', age: '11' }, { name: 'bob', age: '12' } ] }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-21
      • 2021-12-28
      • 2016-11-16
      • 2014-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多