Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ForEach push new item into object

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?

like image 716
Ravi Ram Avatar asked Nov 21 '13 02:11

Ravi Ram


1 Answers

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;

});
like image 71
Josh Avatar answered Oct 19 '22 03:10

Josh