1

How I push objects with same key name into an array using angular.forEach() function ?

for example, I declare an empty array i.e. $scope.arr = [] and an empty object i.e. $scope.obj = {}

Now using angular.forEach() and push() function, how can I get the following result :

$scope.arr = [{msg: ''}, {msg: 'please, enter no.'}, {msg: ''}]

my JS code

$scope.arr = []
$scope.obj = {}
       angular.forEach(['12', 'Please, enter no.', '43'], function (value, index) {
           if (isNaN (value)) {
                $scope.obj['msg'] = 'Please, enter no.';
                $scope.arr.push($scope.obj);
           }
           else {
                $scope.obj['msg'] = '';
                $scope.arr.push($scope.obj);
           }
       });

Current wrong output : $scope.arr = [{msg: 'please, enter no.'}, {msg: 'please, enter no.'}, {msg: 'please, enter no.'}]

Expected Output : $scope.arr = [{msg: ''}, {msg: 'please, enter no.'}, {msg: ''}]

I knew why I got wrong output because all the msg keys are updated with last value of array, but I could not find the remedy for this.

Please, help me.....

2 Answers 2

1

Why create a $scope object? As you have found this will just keep adding the same object reference to your array. How about:

angular.forEach(['12', '43', 'Please, enter no.'], function (value, index) {
    if (isNaN (value)) {
        $scope.arr.push({ msg: 'Please, enter no.' });
    }
    else {
        $scope.arr.push({ msg: '' });
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Lex : thanks yaar (means friend in Indian language).. nice trick. It works.
0

Now, I got reason about wrong output of above code is that I wrongly declared $scope.obj = {} outside the angular.forEach () function but it should be declared inside it. By doing so, everytime new object will created in each iteration.

Corrected JS Code :

$scope.arr = []
angular.forEach(['12', 'Please, enter no.', '43'], function (value, index) {
           $scope.obj = {}
           if (isNaN (value)) {
                $scope.obj['msg'] = 'Please, enter no.';
                $scope.arr.push($scope.obj);
           }
           else {
                $scope.obj['msg'] = '';
                $scope.arr.push($scope.obj);
           }
       });

1 Comment

Then why are you creating it as a scope object at all? You are probably better of just omitting that part instead as it provides no additional functionality but registers the object to the scope during each iteration.

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.