簡體   English   中英

如何在AngularJS中創建一個類似於對象數組中的對象的空對象?

[英]How to create an empty object similar to an object from a array of objects in 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"
    }
];

我怎樣才能做到這一點?

假設您想要模擬的數組中始終存在某些內容 ,請獲取第一個對象,循環鍵並創建一個空白對象:

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM