1

我想通过 JSON,如果某个条件适用,则在该索引中推送一些额外的元素。

我有这个JS代码:

$scope.addRoleToUser = function() {
    var userid = $scope.selectedUser;
    var tmpdata = [];
    var index = 0;
    //alert(userid);
    angular.forEach($scope.users, function(data) {

        if (data.id == $scope.selectedUser) {
            tmpdata.push(data,{"roles":[{"id":"00","name":"newrole"}]});
        }
        else {
            tmpdata.push(data); 
        }
        index++;
    });
    $scope.users = tmpdata; 
};

这是我最初的 JSON 元素:

$scope.users = [
                    {"id":"0","name":"User1","roles":[{}]},
                    {"id":"1","name":"User2","roles":[{}]},
                ]

我试图让它在函数运行后看起来像这样:

$scope.users = [
                    {"id":"0","name":"User1","roles":[{"id":"00","name":"newrole"}]},
                    {"id":"1","name":"User2","roles":[{}]},
                ]

但相反,我得到了这个:

[{"id":"0","name":"User1","roles":[{}]},{"roles":[{"id":"00","name":"newrole"}]},{"id":"1","name":"User2","roles":[{}]}]
4

3 回答 3

1

只需在你的函数中替换它

if (data.id == $scope.selectedUser) {
    data.roles = [{"id":"00","name":"newrole"}];
}

或者,如果您知道角色不为空,您可以执行以下操作:

if (data.id == $scope.selectedUser) {
    data.roles.push({"id":"00","name":"newrole"});
}

在此行之后,您可以将数据添加到 tmpdata!

该片段现在看起来像这样:

if (data.id == $scope.selectedUser) {
    data.roles = [{"id":"00","name":"newrole"}]}); //or the other one
}
tmpdata.push(data); 
于 2013-05-28T13:15:30.650 回答
1

forEach()回调中,您只是在处理对象,因此,您可以直接在回调中修改它们:

angular.forEach($scope.users, function(data) {
    if (data.id == $scope.selectedUser) {
        data.roles = [{"id":"00","name":"newrole"}];
    }
});

data同样,您可以通过操作相应的对象来修改每个条目的几乎任何内容。

示例小提琴

于 2013-05-28T13:19:04.827 回答
0

Array.prototype.push 方法是可变的:(https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/push)。

当您调用时tmpdata.push(a,b,c),您实质上是将数组附加[a,b,c]tmpdata.

您还可以通过以下方式分解问题:

$scope.addRoleToUser = function() {
  var thisUserid = $scope.selectedUser;

  function addRolesFor(user) {
    if (user.id === thisUserId){ user.roles = [{"id":"00","name":"newrole"}] };
    return user;
  }
  retrun $scope.users.map(addRoles);
}

请使用map适合您环境的功能(如_.map),因为Array.prototype.map并非所有浏览器都支持该方法。

于 2013-05-28T13:32:55.427 回答