AngularJS ForEach push new item into object

All we need is an easy explanation of the problem, so here it is.

I have a JavaScript object which has a list of retailers

var listRetailers = [
{"url":"http://www.fake1.com", "img":"images/1logo.jpg"},
 {"url":"http://www.fake2.com", "img":"images/2logo.gif"},
 {"url":"http://www.fake3.com", "img":"images/3logo.gif"},
 ]

I would like to PUSH a new key:value into each item:

object.push("storeNumber": "1");

So the updated JavaScript object will be

var listRetailers = [
{"url":"http://www.fake1.com", "img":"images/1logo.jpg", "storeNumber":"1"},
 {"url":"http://www.fake2.com", "img":"images/2logo.gif", "storeNumber":"1"},
 {"url":"http://www.fake3.com", "img":"images/3logo.gif", "storeNumber":"1"},
 ]

Within my angular controller I have

$scope.retailers = listRetailers ;

angular.forEach($scope.retailers, function(obj){
          obj.push("storeNumber": "1");
        });

The error states: Object # has no method ‘push’

What am I missing here?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

That’s because obj refers to your retailer object and is not an array. If you want to add properties to it, you can just define them using either the bracket [] notation, or by using the dot . notation.

angular.forEach($scope.retailers, function(obj){

   //Using bracket notation
   obj["storeNumber"] = 1;

   //Using dot notation
   obj.storeNumber = 1;

});

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply