Having difficulty pushing data on an array using foreach

171 views Asked by At

I am using the following example

https://docs.angularjs.org/api/ng/directive/ngController

in the above mentioned example I have added new button called save. In save I am trying to push all the contacts into an array. Following is my code for Save.

$scope.SaveContact = function () {

    var len = $scope.contacts.length;
    var contactlist = [];
    angular.foreach($scope.contacts, function (value, key) {
        contactlist.push( value.type + ':' + key);
    }, contactlist);

    console.log(contactlist);

};

Please can someone help me solve this.

2

There are 2 answers

2
Catalin Iosif On

You should fix the spelling of .foreach first.

Since you are iterating over an array, the key will be the index, and the value will be the object stored in the array. You are also doing a string concat (key +":"+ value) so you will get an array like this:

["0, [Object Object]", "1, [Object Object]", ...]

I would suggest using the Array prototype .forEach instead of the angular .forEach, since you don't need to use the keys (array index in this case).

$scope.SaveContact = function () {

  var contactlist = [];
  $scope.contacts.forEach(function(contact) {
    contactlist.push(contact.type + ":" + contact.value);
  });

  console.log(contactlist);

};

If you want to use angular.forEach I would say:

angular.forEach($scope.contacts, function(value, key) {
  this.push(value.type + ': ' + value.value);
}, contactlist);

But I don't recommend it since it's easy to confuse the value parameter in the angular.forEach callback with the "value" key of the objects stored in the $scope.contacts array.


I assumed you are using the following format for $scope.contacts from the angular documentation:

$scope.contacts = [
  {type:'phone', value:'408 555 1212'},
  {type:'email', value:'[email protected]'} ];

This way, you should get an array like this:

["phone:408 555 1212","email:[email protected]"];

Also, I would suggest using $scope.contactlist instead of var contactlist, so the list is accessible outside the SaveContact function.

0
Iwan1993 On

Try the following

var contactlist = [];
angular.forEach($scope.contacts, function(value, key) {
  this.push(key + ': ' + value);
}, contactlist);

If value.type exists you can use this.push(key + ': ' + value.type);