1

我有两个可观察的数组:

var viewModel = {
    PositionTypes: ko.observableArray([]),
    Users: ko.observableArray([])
}

位置视图模型

var positionViewModel = function (data) {
        var _self = this;
        _self.PositionName = ko.observable(data.PositionName);
        _self.PositionRank = ko.observable(data.PositionRank);
        _self.ContentRole = ko.observable(data.ContentRole);
    }

    positionViewModel.AddPositions = function (data) {
        $.each(data, function (index, value) {
            positionViewModel.PushPosition(value);
        });
    };

    positionViewModel.PushPosition = function (postion) {
        viewModel.PositionTypes.push(new positionViewModel(position));
    };

用户视图模型

    // the ViewModel for a single User
    var userViewModel = function (data) {
        var _self = this;
        _self.ID = ko.observable(data.ID);
        _self.Name = ko.observable(data.Name);
        _self.Email = ko.observable(data.Email);
        _self.ContentRole = ko.observable(data.ContentRole);
    };

    userViewModel.AddUsers = function (data) {
        $.each(data, function (index, value) {
            userViewModel.PushUser(value);
        });
    };


    userViewModel.PushUser = function (user) {
        viewModel.Users.push(new userViewModel(user));
    };

我如何使用 linq.js 以便循环遍历每个位置,以便获得每个位置的所有用户?

foreach( each position in positions)
{
    foreach(each user in users)
    { list of users for the position}
}
4

2 回答 2

0

使用 linq.js,您可以对要比较的列执行连接。

假设您在 s 之间加入ContentRole

var query = Enumerable.From(viewModel.PositionTypes())
    .GroupJoin(viewModel.Users(),
        "$.ContentRole()",  // position selector
        "$.ContentRole()",  // user selector
        "{ Position: $, Users: $$.ToArray() }")
    .ToArray();

所以我想你想创建一个包含所有职位和用户名映射的对象。您可以使用该函数创建这样一个对象Aggregate(),将所有结果收集到一个对象中。

var userPositions = Enumerable.From(this.PositionTypes())
    .GroupJoin(this.Users(),
        "$.ContentRole()",  // position selector
        "$.ContentRole()",  // user selector
        "{ Position: $, Users: $$ }") // group all users per position
    .Aggregate(
        {}, // start with an empty object
        function (userPositions, x) {
            var positionName = x.Position.PositionName(),
                userNames = x.Users.Select("$.Name()").ToArray();

            // add the new property
            userPositions[positionName] = userNames;
            return userPositions;
        }
    );
于 2013-10-01T16:24:39.887 回答
0

您还可以使用ko.utils.arrayForEach如下:

ko.utils.arrayForEach(viewModel.PositionTypes(), function(position){    
     var usersInPosition = ko.utils.arrayFilter(viewModel.Users(), function(user){
          return user.ContentRole() == position.ContentRole();
     });
     ko.utils.arrayForEach(usersInPosition, function(user){        

    });
});

见文档

我希望它有所帮助。

于 2013-10-01T07:25:32.257 回答