Javascript 如何 JSON.stringify 对象数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35081851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:15:27  来源:igfitidea点击:

How to JSON.stringify an array of objects

javascriptarraysjsonobjectstringify

提问by crmepham

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

我正在尝试JSON.stringify()以下键/值对,其中值是一个对象数组。

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: Converting circular structure to JSON

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

                ^

类型错误:将圆形结构转换为 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 usersdata structure:

添加users数据结构:

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

Added function to add user to users 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 JavaScript array containing an object as well as key/value pairs inside an object.

添加了包含对象以及对象内的键/值对的 JavaScript 数组的屏幕截图。

enter image description here

enter image description here

Added screen capture of the clients array containing WebSocket objects. enter image description here

添加了包含 WebSocket 对象的客户端数组的屏幕截图。 enter image description here

How do I correctly "stringify" {key: arrayOfObjects[{key:value,key:{}},{},{}]}?

我如何正确地“字符串化” {key: arrayOfObjects[{key:value,key:{}},{},{}]}

采纳答案by Shaun Sharples

var data = { };
data.onlineUsers = getUsersInRoom();

var string = JSON.stringify(data);

Would this work for you?

这对你有用吗?

edit

编辑

I just noticed your error is circular type, your user or room object is probably creating a circular reference.

我刚刚注意到您的错误是循环类型,您的用户或房间对象可能正在创建循环引用。

User > Room > User > Room etc...

用户 > 房间 > 用户 > 房间等...