如何在AngularJS中创建一个类似于数组对象中的空对象?

3

我有以下对象数组:

$scope.users = [
    {
        ID: "1",
        Name: "Hege",
        Username: "Pege",
        Password: "hp",
    },
    {
        ID: "2",
        Name: "Peter",
        Username: "Pan",
        Password: "pp"
    }
];

我需要创建一个类似的对象,其中所有值都为空,如下所示:
$scope.newUser = {
    ID: "",
    Name: "",
    Username: "",
    Password: ""
}

这样我就可以将它推送到相同的数组中($scope.users.push($scope.newUser);),让它看起来像这样:

$scope.users = [
    {
        ID: "1",
        Name: "Hege",
        Username: "Pege",
        Password: "hp"
    },
    {
        ID: "2",
        Name: "Peter",
        Username: "Pan",
        Password: "pp"
    },
    {
        ID: "",
        Name: "",
        Username: "",
        Password: ""
    }
];

然而,数组$scope.users并不总是具有相同对象的数组。我需要使其能够在我更改数组为其他内容时正常工作,例如像这样:

$scope.users = [
    {
        SID: "pepe",
        Name: "Peter",
        School: "Primary School"
    },
    {
        SID: "hepe",
        Name: "Hege",
        School: "Junior School"
    }
];

我该如何做到这一点?


你确定数组里只有同样结构的对象吗?不管怎样,Angular并没有提供清除对象字段的方法,但你可以简单地编写自己的函数。 - Grundy
你为什么要这样做?我知道这不是一个答案,但它似乎违反了我所谓的良好编程的原则。拥有一组事物包含未定义的事物是不合适的。 - Doug Moscrop
1个回答

4

假设你想要模仿数组中的一些东西,获取第一个对象,循环键并创建一个空对象:

if ($scope.users.length) {
    var defaultUser = $scope.users[0];

    $scope.newUser = {};
    for (var key in defaultUser) {
        $scope.newUser[key] = "";
    }

    $scope.users.push($scope.newUser);
}

或者如果您有有限数量的事物,则为它们创建声明。否则,这就是最好的选择。 - Doug Moscrop

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接