最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to iterate over an array of objects in the request body - Stack Overflow

programmeradmin1浏览0评论

I am sending an array of objects to the server (as below), the server must receive the objects and add them to the mongodb. I'm new to node.js, I usually deal with the keys inside the rcevived request body (req.body). But here, the keys are the objects. How can I iterate over them?

[
    {
        id: "1",
        Name: "John"
    },
    {
        id: "2",
        Name: "Mark"
    },
    {   
        id: "3",
        Name: "Domi"
    }  
]

Server Code:

server.get('/user', function (req, res, next) {
//iterate over the objects in req.body
});

When I want to send one object I can easily get the the request content by req.body.id and req.body.Name, so how to do it with multiple objects inside the request body?

I am sending an array of objects to the server (as below), the server must receive the objects and add them to the mongodb. I'm new to node.js, I usually deal with the keys inside the rcevived request body (req.body). But here, the keys are the objects. How can I iterate over them?

[
    {
        id: "1",
        Name: "John"
    },
    {
        id: "2",
        Name: "Mark"
    },
    {   
        id: "3",
        Name: "Domi"
    }  
]

Server Code:

server.get('/user', function (req, res, next) {
//iterate over the objects in req.body
});

When I want to send one object I can easily get the the request content by req.body.id and req.body.Name, so how to do it with multiple objects inside the request body?

Share Improve this question edited Feb 25, 2015 at 20:52 zoma.saf asked Feb 25, 2015 at 16:56 zoma.safzoma.saf 5683 gold badges6 silver badges14 bronze badges 4
  • 2 Are you sure those outer {}s aren't a []? It's probably an Array. – Jacob Commented Feb 25, 2015 at 17:00
  • Possible duplicate - stackoverflow./questions/7440001/… – user3970381 Commented Feb 25, 2015 at 17:01
  • You have mentioned in title as Array of objects..but your code doesn't depicts the same.. – Rakesh_Kumar Commented Feb 25, 2015 at 17:03
  • @Jacob fixed for convenient understanding – zoma.saf Commented Feb 25, 2015 at 20:52
Add a ment  | 

1 Answer 1

Reset to default 4

something like this:

var bodyParser = require('body-parser');

server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));

server.get('/user', function (req, res, next) {
   var data = req.body;

   data.forEach(function (item) {
       console.log(item.id);
       console.log(item.Name);
   });
}); 
发布评论

评论列表(0)

  1. 暂无评论