[英]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.