1

I'm having this collection of objects which are inside a html text area:

{"name":"John", "lname":"Doe","company":"example company","email":"[email protected]"},{"name":"Katie","lname":"Jake","company":"example company","email":"[email protected]"},
...
...
...

Is there a way to send the whole collection to node js and iterate through it to get values of objects?

My AJAX code:

  $.ajax({
    type: "POST",
    url: "https://example.com/nodeapp",
    data: '['+document.getElementById("list").value+']',
    success: function(data) {
      console.log(data);
    }
  });

I tried to do a foreach on req.body, but it doesn't seem to work:

var arr = req.body;

arr.foreach(element=>{
console.log(element.email);
})

Gives the error:

TypeError: arr.foreach is not a function
Shri
  • 709
  • 1
  • 7
  • 23

2 Answers2

0

At first , you have to parse the body by using JSON.parse() function . Like this :

var arr = JSON.parse(req.body);

arr.forEach(element=>{
console.log(element.email);
});

The javascript's foreach also defined as arr.forEach(...) not arr.foreach(...) .

Ali Reza
  • 105
  • 1
  • 7
0

I found my problem! Incase someone is stuck with the same thing, the whole thing was a string:

'[{"name":"John", "lname":"Doe","company":"example company","email":"[email protected]"},
{"name":"Katie","lname":"Jake","company":"example company","email":"[email protected]"},
...
...]'

Which was considered as one property in JSON which has no value while the server received it. Pretty much like this:

{
"<<the array in string format>>" : ""
}

How I fixed this was, I pushed the objects separately into a new array and sent it to server with JSON content type. (Which was an actual array of objects)

Shri
  • 709
  • 1
  • 7
  • 23