将元素推入JSON对象

时间:2013-05-28 13:09:03

标签: javascript json angularjs

我想通过一个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":[{}]}]

3 个答案:

答案 0 :(得分: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); 

答案 1 :(得分:1)

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

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

类似地,您可以通过操纵相应的data对象来修改每个条目的几乎任何内容。

Example Fiddle

答案 2 :(得分: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方法。