如果value在多维数组中

时间:2015-05-10 17:58:00

标签: jquery arrays multidimensional-array

我的$.getJSON功能出现问题,首先我将所有朋友都存储在这样的数组中:

var friends = [];
friends.push({
    user: {
        username: value.username,
        uuid: value.uuid,
        accepted: value.accepted,
        sent: value.sent
    }
});

这是来自$.getJSON函数的数据并且工作正常。

然后我有一个搜索功能,我在这里搜索我的数据库中的用户名:

$(document).on('keyup', '.search', function() {
        $.getJSON('url?username='+$(this).val(), function(data){
            $.each(data, function(index, value){
                friends.filter(function (friend) {
                    if(friend.user.username == value.username){
                       //Append custom
                    } else {
                        //append data from JSON
                    }
                });
            });
        });
    });

如果friends数组有一个对象,这可以正常工作。但如果它是空的,没有任何事情发生,它不会附加任何东西。

这里有什么问题?任何帮助表示赞赏

1 个答案:

答案 0 :(得分:2)

您应该使用filter通过评估您的案例是否为true来返回数组中的匹配项。

var matches = friends.filter(function (friend) {
    return friend.user.username == value.username
});
if (matches.length > 0) {
    //you had a match in the friends array
    console.log(matches[0]);
} else {
    //you didn't have a match in the friends array
}

这是fiddle demonstrating the idea