Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object to json string in node.js

I have a problem with node.js to object to json string

var chat = {};
chat.messages = [];
chat.messages['en'] = [];
chat.messages['fr'] = [];
console.log(chat.messages)
console.log(JSON.stringify(chat.messages));

I got

[ en: [], fr: [] ]
[]

I don't know why this is not correctly convert

like image 877
Ajouve Avatar asked Jan 20 '26 11:01

Ajouve


1 Answers

On this line, you initialize chat.messages as an empty array:

chat.messages = [];

Here, you use it as an object:

chat.messages['en'] = [];
chat.messages['fr'] = [];

These lines actually set properties on the array instance. It's curious that Node would include these properties in the normal .toString() result (i.e., that you'd see the set properties as elements of the array on console.log(chat.messages).


In any case, to fix, declare chat.messages as an object:

chat.messages = {};
chat.messages['en'] = [];
chat.messages['fr'] = [];
like image 92
Jon Gauthier Avatar answered Jan 23 '26 01:01

Jon Gauthier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!