AngularJS计算函数中的字符串,以调用json列表上的属性

AngularJS evaluate a string in a function to call property on json list

本文关键字:json 调用 列表 属性 计算 函数 字符串 AngularJS      更新时间:2023-09-26

我希望我能给它一个更具描述性的标题,但我真的不知道我要做什么的名字

$scope.users =
    {
        // list name and the "title" must be the same
        Guest:
        {
            title: 'Guest',
            list:
            [
                { id: "0", name: "Stephen" },
                { id: "1", name: "Mitch"},
                { id: "2", name: "Nate"},
                { id: "3", name: "Rob" },
                { id: "4", name: "Capt. Jack"},
                { id: "5", name: "Herman" }
            ]
        },
        Admin:
        {
            title: 'Admin',
            list:
            []
        }
    };

我需要动态评估一个字符串("Guest"或"Admin"或任何其他尚未创建的用户组),以便将用户从一个用户组移动到另一个。

我正在使用的功能看起来像:

$scope.moveUser = function(fromId, toId, index) {
        scope.users.toId.list.push(scope.users.fromId.list[index]);
        scope.users.fromId.list.splice(index, 1);
};

其中"fromId"answers"toId"是计算为用户组名称("Admin"或"Guest")的字符串。现在,该函数正试图找到一个名为"toId"的JSON字段,当找不到任何字段时会出错。我如何首先评估字符串,以便如果toId=="Guest"和fromId=="Admin",我的函数变为:

scope.users.Guest.list.push(scope.users.Admin.list[index]);
scope.users.Admin.list.splice(index, 1);

$scope.moveUser函数更改为

$scope.moveUser = function(fromId, toId, index) {
    $scope.users[toId].list.push($scope.users[fromId].list[index]);
    $scope.users[fromId].list.splice(index, 1);}

它真的是工作

如果我理解正确:

$scope.moveUser = function(fromId, toId, index) {
        if (users.hasOwnProperty(fromId) && users.hasOwnProperty(toId)) {
          scope.users.toId.list.push(scope.users.fromId.list[index]);
          scope.users.fromId.list.splice(index, 1);
          return true;
        } else {
          return false;
        }
};