AngularJS ForEach将新项目推送到对象中 [英] AngularJS ForEach push new item into object

查看:85
本文介绍了AngularJS ForEach将新项目推送到对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含零售商列表的JavaScript对象

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");

因此更新后的JavaScript对象将是

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'

我在这里缺少什么?

推荐答案

那是因为 obj 是指您的零售商对象和不是数组如果要向其添加属性,您可以只需使用括号 [] 表示法或使用点表示法来定义它们。

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;

});

这篇关于AngularJS ForEach将新项目推送到对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆