【问题标题】:Unable to iterate through JSON array无法遍历 JSON 数组
【发布时间】:2016-08-07 15:14:05
【问题描述】:

我有一个返回数组的 api(在 NODEJS 中)响应:

res.json(friends)
[
    {
        "id": 7795239,
        "username": "janesmith"
    },
    {
        "id": 1363327,
        "username": "johnsmith"
    }
]

但是当我想在发送此响应之前遍历数组时,我找不到执行此操作的方法。 users.length 不存在,for(var key users) 也不起作用。

如何解决?

编辑:获取数组的代码:

User.find({}, function(err, users){
    if(err) res.send(err);
    var friends;
    var result = 'this will hold the result';

    for(var key in users){
        if(users[key].username == req.decoded.username) {
            friends = users[key].friends;
        }
    }

    // here I want to do things with the list of friends, so this is the place where I need to iterate over it

    res.json(result);
});

这是userserr 的日志结果

users: 
    [
        {
            "_id": "5710b02c7787794009325f62",
            "username": "demouser",
            "__v": 0,
            "friends": 
            [
                {
                    "username": "janesmith",
                    "id": 7795239
                },
                {
                    "username": "johnsmith",
                    "id": 1363327
                }
            ]
        }
    ]   
err: null

这是钥匙的日志:

toObject
toJSON
items
db
discriminators
__v
id
_id
friends
password
username
userID
schema
collection
comparePassword
save
$__delta
$__version
increment
$__where
remove
model
$__buildDoc
init
$__storeShard
hook
pre
post
removePre
_lazySetupHooks
update
set
$__shouldModify
$__set
getValue
setValue
get
$__path
markModified
$__try
modifiedPaths
isModified
isDirectModified
isInit
isSelected
validate
invalidate
$__reset
$__dirty
$__setSchema
$__registerHooks
$__error
$__doQueue
$toObject
inspect
toString
equals
populate
populated
$__fullPath
domain
_events
_maxListeners
setMaxListeners
getMaxListeners
emit
addListener
on
once
removeListener
removeAllListeners
listeners
listenerCount

【问题讨论】:

  • 你能发布一个演示来重现这个问题吗?
  • 需要看更多代码才能回答。你能显示你分配数组的位置吗?
  • 如果您将该 JSON(当然没有 res.json(users))解析为一个对象,那么您应该能够毫无问题地迭代其属性。
  • 如果users.length 不存在,则它既不是数组也不是字符串。当您登录/检查users 时会得到什么?
  • console.log(err);console.log(users); 的结果是什么?

标签: javascript arrays json node.js


【解决方案1】:

您的 API 的 find 方法似乎返回的是对象而不是数组。

User.find({}, function(err, users){

    /* You expect users to be an array, but I suspect this is actually what it is:

    users = {
        "_id": "5710b02c7787794009325f62",
        "username": "demouser",
        "__v": 0,
        "friends": 
        [
            {
                "username": "janesmith",
                "id": 7795239
            },
            {
                "username": "johnsmith",
                "id": 1363327
            }
        ]
    }
    */

    if(err) res.send(err);
    var friends;
    var result = 'this will hold the result';

    /* Try without the loop to confirm:
    for(var key in users){
        if(users[key].username == req.decoded.username) {
            friends = users[key].friends;
        }
    }*/

    if(users.username == req.decoded.username) {
        friends = users.friends;
    }

    // here I want to do things with the list of friends, so this is the place where I need to iterate over it

    res.json(result);
});

【讨论】:

  • 试过这个,但后来在控制台中得到了[]
  • 好吧,显然users 有一个名为friends 的属性,它是一个空数组,这不是您所期望的,但它确实有username 匹配req.decoded.usernamefriends将是undefined。我仍然相信这个 API 不会返回你想要的东西,而且你发布的 users 的值并不是它的实际值。
【解决方案2】:

只需将您的结果变量初始化为一个数组,然后将您希望匹配的用户推送到该数组中并返回它。

User.find({}, function(err, users){
    if (err) res.send(err);

    var result = [];
    for (var key in users) {
        if (users[key].username == req.decoded.username) {
            var friends = users[key].friends;
            for (var i = 0; i < friends.length; i++) {
                // Do stuff with each friend here, as required.
            }

            result.push(users[key]);

            // OR this, depending on whether it is users or friends you're trying to return.
            result.push(friends[i]);
        }
    }

    res.json(result);
});

【讨论】:

  • 这应该是评论,而不是答案。
  • 不,这是他的问题的答案。他只需要将 JSON 解析为一个对象,就完成了。这个答案说明了如何使用他给出的 JSON 字符串来做到这一点。我已经说明,在正确解析 JSON 之后,完全可以访问数组的长度属性,然后访问该数组中对象的属性。
  • 我在尝试解析时出错:undefined:1 [ { id: 7795239, username: 'janesmith' }, ^ SyntaxError: Unexpected token i at Object.parse (native)
  • 就像我说的,这不是答案......
  • 即使它完全回答了他的问题?很有趣。
【解决方案3】:
var array1 = ['a', 'b', 'c'];

array1.forEach(function(element) {
  console.log(element);
});

// expected output: "a"
// expected output: "b"
// expected output: "c"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-26
    • 2011-02-05
    • 2018-06-05
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    相关资源
    最近更新 更多