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

时间:2015-05-13 14:22:21

标签: javascript arrays json angularjs

我有以下对象数组:

$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"
    }
];

我该怎么做?

1 个答案:

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