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.

2
  • 4
    They syntax your first array is wrong, you cannot have keys for array items Commented Nov 12, 2015 at 23:57
  • Thanks, @mcfedr . I have changed array to object and everything is working fine. Just [ ] to { }. Commented Nov 13, 2015 at 10:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.