How to JSON. Build an array of objects

I am trying to JSON.stringify() following key / value pair, where the value is an array of objects.

 var string = JSON.stringify({onlineUsers : getUsersInRoom(users, room)}); 

This is incorrect and gives the following error:

var string = JSON.stringify ({onlineUsers: getUsersInRoom (users, room)});

  ^ 

TypeError: convert circular structure to JSON

This is the method:

 function getUsersInRoom(users, room) { var json = []; for (var i = 0; i < users.length; i++) { if (users[i].room === room) { json.push(users[i]); } } return json; } 

Added users data structure:

 [ { id:1, username:"", room:"room 1", client: { sessionId:1, key:value } }, { // etc } ] 

Added function to add user to user array.

 function addUser(client) { clients.push(client); var i = clients.indexOf(client); if (i > -1) { users.push({ id : i, username : "", room : "", client : clients[i] }); } } 

Added screen capture of the JavaScript array containing the object, as well as key / value pairs inside the object.

enter image description here

Added screen capture of a client array containing WebSocket objects. enter image description here

How to "back up" {key: arrayOfObjects[{key:value,key:{}},{},{}]} ?

+5
source share
1 answer
 var data = { }; data.onlineUsers = getUsersInRoom(); var string = JSON.stringify(data); 

Will this work for you?

change

I just noticed that your error is circular, your custom or indoor object is probably creating a circular link.

User> Room> User> Room, etc.

+3
source

Source: https://habr.com/ru/post/1241802/


All Articles