如何使用循环迭代将值推送到数组中

时间:2018-02-07 06:11:29

标签: angularjs

$http.get('v1/item_id/' + item_id + '/user_id/' + auth.getCurrentUser.user_id)
    .success(function(res) {
        var data = res.data;
        var users_children = [];
        var new_data = [];
        for (var i = 0; i < data.length; i++) {
            if (data[i].user_id == auth.getCurrentUser().children[i].user_id) {
                users_children.push({
                    'user_id': data[i].user_id
                });
                users.filter(function(item) {
                    if (item.user_id != users_children[i].user_id) {
                        new_data.push(item);
                        deferred.resolve(new_data);
                    }
                });
                return;
            } else {
                users.children = "Not data found";
                deferred.resolve(users.children);
                return;
                console.log("Does not exist");
            }
        }
    })

//期望它循环遍历所有数据的user_id,并检查当前用户的user_id,如果它与push_children匹配

//但是它检查数组的第一个对象是什么,如果匹配则返回第一个子节点,否则停止执行。请指导如何解决此问题。

1 个答案:

答案 0 :(得分:0)

我会尝试对您的代码进行更改,我从评论中理解

$http.get('v1/item_id/' + item_id + '/user_id/' + auth.getCurrentUser.user_id)
    .success(function(res) {
        var data = res.data;
        var users_children = [];
        var new_data = [];
        for (var i = 0; i < data.length; i++) {
            if (data[i].user_id == $scope.isUser(data[i].user_id)) {
                users_children.push({
                    'user_id': data[i].user_id
                });
                users.filter(function(item) {
                    if (item.user_id != users_children[i].user_id) {
                        new_data.push(item);
                        deferred.resolve(new_data);
                    }
                });
                return;
            } else {
                users.children = "Not data found";
                deferred.resolve(users.children);
                return;
                console.log("Does not exist");
            }
        }
    })

创建一个单独的方法来检查user_id是否存在于某个用户列表中

$scope.isUser = function(user_id) {
    var user_ids = auth.getCurrentUser().children.map(function(x){
        return x.user_id;
    });
    return (user_ids.indexOf(user_id) !== -1)
}