Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an empty object similar to an object from a 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 this,

$scope.newUser = {
    ID: "",
    Name: "",
    Username: "",
    Password: ""
}

so that I can push it to the same array ($scope.users.push($scope.newUser);), to get it look 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, the array $scope.users will not always have the array of same objects. I need it to work even if I change the array to something different, for example, like this:

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

How can I do this?

like image 933
Dishon Avatar asked Jan 01 '26 01:01

Dishon


1 Answers

Assuming there's always something in the array you want to mimic, get the first object, loop the keys and make a blank 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);
}
like image 101
tymeJV Avatar answered Jan 03 '26 16:01

tymeJV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!