Matt Altepeter Matt Altepeter - 2 months ago 10
Javascript Question

Array is empty in res.json() but it exists before and after the res.json() call

I am trying to send a json response via Express through

res.json()
, but the value of the
records
in the object sent via
res.json()
is empty.

I have this block of code:

stats.activities(params).then(res => {
processActivities(res, response => {
console.log(response); // => logs response properly
globalRes.json({
ok: true,
message: '',
records: response // response is an empty array
});
console.log(response); // => logs response properly
});
});


Here are my
console.logs()
:

[ players: [ [ [Object], [Object], [Object] ] ] ]
[ players: [ [ [Object], [Object], [Object] ] ] ]


And here is the response I am getting back (in Postman):

{
"ok": true,
"message": "",
"records": []
}


Any idea as to what could be causing this?

Answer

This isn't a valid array:

[ players: [ [ [Object], [Object], [Object] ] ] ]

Arrays have numerical indexes, and a length. Your array has a property called player, which will be ignored when calling JSON.stringify on it.

Here's an example demonstrating the problem:

let a    = [];
a.player = 'jack';
console.log(JSON.stringify(a)); // []

You probably want an object:

let a    = {};
a.player = 'jack';
console.log(JSON.stringify(a)); // {"player":"jack"}
Comments