How do I create an empty object like an object from an array of objects in AngularJS?
I have the following array of objects:
$scope.users = [
{
ID: "1",
Name: "Hege",
Username: "Pege",
Password: "hp",
},
{
ID: "2",
Name: "Peter",
Username: "Pan",
Password: "pp"
}
];
I need to create a similar object with empty values like
$scope.newUser = {
ID: "",
Name: "",
Username: "",
Password: ""
}
so that I can push it into the same array ( $scope.users.push($scope.newUser);
) so that it looks something like this:
$scope.users = [
{
ID: "1",
Name: "Hege",
Username: "Pege",
Password: "hp"
},
{
ID: "2",
Name: "Peter",
Username: "Pan",
Password: "pp"
},
{
ID: "",
Name: "",
Username: "",
Password: ""
}
];
However, an array $scope.users
will not always have an array of the same objects. I need it to work even if I change the array to something else, like for example:
$scope.users = [
{
SID: "pepe",
Name: "Peter",
School: "Primary School"
},
{
SID: "hepe",
Name: "Hege",
School: "Junior School"
}
];
How can i do this?
+3
source to share
1 answer
Assuming there is always something in the array you want to emulate, get the first object, loop over the keys and make an empty object:
if ($scope.users.length) {
var defaultUser = $scope.users[0];
$scope.newUser = {};
for (var key in defaultUser) {
$scope.newUser[key] = "";
}
$scope.users.push($scope.newUser);
}
+4
source to share