【问题标题】:Correct way to loop through an JSON object [duplicate]循环遍历 JSON 对象的正确方法 [重复]
【发布时间】:2016-08-09 01:31:56
【问题描述】:

Since there seems nobody is able to find a solution for my problem,我想换个方式问我的问题: 循环遍历以下对象的游戏部分的正确方法应该是什么:

[
    {
        "_id": "5710b0ddab8b724011705037",
        "username": "test",
        "name": "testuser",
        "__v": 0,
        "library": {
            "games": [
                {
                    "platform": [
                        "17",
                        "94"
                    ],
                    "name": "Simcity",
                    "id": "37620"
                },
                {
                    "platform": [
                        "146",
                        "20"
                    ],
                    "name": "destiny",
                    "id": "36067"
                }
            ],
            "platforms": [
                {
                    "name": "Xbox360",
                    "id": "20"
                },
                {
                    "name": "PC",
                    "id": "94"
                }
            ]
        }
    }
]

这个对象是通过 mongoose 从 MongoDB 中提取出来的,这一切都发生在我的 NodeJS 应用程序的 API 部分:

.get('/test', function(req, res){
    User.findOne({"username": req.decoded.username}, function(err, user){

        // trying to loop here

    });
})

我已经尝试了我找到的所有方法,但我无法让它发挥作用,所以我想知道你用什么方法来做到这一点,而不会因为我的(可能是错误的)方法和错误而混淆你的视野......

【问题讨论】:

  • JSON 是一种用于数据交换的文本符号。如果您正在处理 JavaScript 源代码,而不是处理 string,那么您就不是在处理 JSON。如果你正在处理一个字符串,第一步是解析它:var o = JSON.parse(stringContainingJSON);
  • 您的编辑显着改变了数据的结构。请确保您的问题是正确的在发布之前,以免浪费大家的时间。
  • 是的,我不知道我复制了错误的部分,我很抱歉
  • 这不是您之前问题的重复的唯一原因是引用结构的差异。随着那个消失,它是一个完全重复的。您可以编辑该问题以添加详细信息等。基本上,您需要使用调试器进行调试。

标签: json node.js mongodb object


【解决方案1】:

使用 for...in 循环遍历 Javascript/JSON 对象

for (variable in object) {...
}

for...in documentation

使用 forEach 循环遍历 Javascript/JSON 数组

arr.forEach(callback[, thisArg])

forEach documentation

【讨论】:

    【解决方案2】:

    更新答案:

    与原始问题相比,您的编辑显着改变了数据结构。

    现在,您有一个 数组,其中包含一个条目,该条目具有 library,它具有 games,因此您将其引用(假设 user 指向整个事物)为 @987654326 @。例如:

    user[0].library.games.forEach(function(entry) {
        // Use `entry` here
    });
    

    var user = [{
      "_id": "5710b0ddab8b724011705037",
      "username": "test",
      "name": "testuser",
      "__v": 0,
      "library": {
        "games": [{
          "platform": [
            "17",
            "94"
          ],
          "name": "Simcity",
          "id": "37620"
        }, {
          "platform": [
            "146",
            "20"
          ],
          "name": "destiny",
          "id": "36067"
        }],
        "platforms": [{
          "name": "Xbox360",
          "id": "20"
        }, {
          "name": "PC",
          "id": "94"
        }]
      }
    }];
    
    user[0].library.games.forEach(function(entry) {
      log(entry.name);
    });
    
    function log(msg) {
      var p = document.createElement('p');
      p.appendChild(document.createTextNode(msg));
      document.body.appendChild(p);
    }

    原答案:

    games 是一个数组,假设您有 o 引用该对象,您可以从 o.user.library.games 引用它。

    有很多方法可以遍历数组(请参阅this answer 了解列表);其中之一是forEach

    o.user.library.games.forEach(function(entry) {
        // Use `entry` here, e.g. `entry.name`, `entry.id`, etc.
    });
    

    例如:

    var o = {
      "user": {
        "name": "testuser",
        "library": {
          "platforms": [{
            "id": "20",
            "name": "Xbox360"
          }, {
            "id": "94",
            "name": "PC"
          }],
          "games": [{
            "id": "37620",
            "name": "Simcity",
            "platform": [
              "17",
              "94"
            ]
          }, {
            "id": "36067",
            "name": "destiny",
            "platform": [
              "146",
              "Xbox360"
            ]
          }]
        }
      }
    };
    o.user.library.games.forEach(function(entry) {
      log(entry.name);
    });
    
    function log(msg) {
      var p = document.createElement('p');
      p.appendChild(document.createTextNode(msg));
      document.body.appendChild(p);
    }

    从您在下面的评论中,听起来结构可能不像您在问题中引用的那样。您可以使用node-inspector 来调试您的NodeJS 代码,在要循环的开始处设置断点,并检查您引用的对象的变量。这将向您展示它的结构。它非常易于安装 (npm install -g node-inspector) 和使用 (node-debug your-main-file.js)。

    【讨论】:

    • 这正是我一直在尝试的,但我总是收到错误 user.library.games.forEach(function(entry) { TypeError: user.library.games.forEach is not a function
    • @stijnpiron:注意我开头的o.。您在顶级对象上有一个 user 键;顶级对象本身不是用户。如果您已经掌握了这一点,那么您所拥有的与您的问题中所引用的不同,或者您使用的是没有 forEach非常 旧 JavaScript 引擎(于 2009 年推出) ,作为 ES5 的一部分);虽然如果您使用的是 Node,我认为没有哪个版本没有它。
    • 我已经更新了我的问题,数据是获取的,不是硬编码的,所以我没有“o”变量...
    • @stijnpiron:你有从 some 变量引用的数据。 o 是一个示例
    • 当我尝试使用 user[0] 时,我得到一个 TypeError: Cannot read property 'library' of undefinederror...
    猜你喜欢
    • 1970-01-01
    • 2016-07-08
    • 2015-03-18
    • 2015-05-16
    • 2021-10-07
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    相关资源
    最近更新 更多