7

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?

2
  • Which part of this do you think involves JSON? Commented Nov 21, 2013 at 5:14
  • @meagar The updating of json object. Commented Nov 21, 2013 at 20:49

1 Answer 1

22

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;

});
Sign up to request clarification or add additional context in comments.

2 Comments

Is there any reason to choose one over the other, except for personal preference?
@MatthewT.Baker - Absolutely. Most of the time you should be using dot notation for clairty, but the bracket notation allows you to do things that simply aren't possible using dot notation. For instance you could use a computed property name obj["base" + num], or you might want an identifier that has characters that would otherwise not be valid syntax using dot notation. obj["I have spaces"]

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.