3

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?

2
  • are you sure that in array will be only objects with same structure? anyway angular not provide method for cleaning object fields, but you can simple write your own function Commented May 13, 2015 at 14:25
  • Why are you doing this? I know that's not an answer, but it just seems to violate what I would call good programming. Having a set of things contain the undefined thing smells. Commented May 13, 2015 at 14:36

1 Answer 1

4

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Or if you have a finite number of things, then create the declarations for them. Otherwise this is about as good as it gets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.