2

Brief version

I want to know how can I send below array of objects in NodeJS to an app in AngularJS.

var players = 
[ 
  Footer: { username: 'Footer', hp: 200, exp: 1 },
  Barter: { username: 'Barter', hp: 200, exp: 1 }
];

I've tried to send it in many ways, but I always receive an empty array on the AngularJS side.

Extended question

On the server, I'm assigning new users to an array players. I want to found the user object passing username as some index to the array. I've successfully done it using .push method, but it don't provide a way to access it with indexes. So, I've started to use the bracket notation to create objects on my array and, later on, access then using this:

//players.push(user); //This does work, but won't be indexed.
var username = user.username; //This is the new user object.
players[username] = user; //Using bracket notation to create object

After that, I have a route that responds with this players array. I've tried both res.send() and res.json(). The array is being console.log() before sent and it is fine. But the response comes as an empty array.

On the client-side, I'm logging res.data, which just logs [].

I'm kind of stuck in here. If needed be, I can put more code here. Or, you can access this GitHub project with the full code.

Community
  • 1
  • 1
Rodmentou
  • 1,610
  • 3
  • 21
  • 39

1 Answers1

1

If players is an array, you have to use indices to fill it instead of username strings. JSON.stringify will ignore non-integer keys on array objects.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375