将数组推入JSON对象,Javascript(Push array into JSON Object, Javascript)

编程入门 行业动态 更新时间:2024-10-28 04:21:05
数组推入JSON对象,Javascript(Push array into JSON Object, Javascript)

我正在努力编写一个有角度的应用程序。 将空数组推入对象时遇到问题。

我收到一个错误:

TypeError:无法读取未定义的属性“push”

我有一个名为items的对象,如下所示:

Object { "Name": "name", "Description": "description" }

我想将一个空数组推入可以包含另一个数组的对象。 像这样的东西。

Object { "Name": "name", "Description": "description", "Related Items": { Item1:{...}, Item2:{...}, ... } }

我的控制器在调用时执行此操作:

$scope.push = function () { $scope.item.push({"Related Items":[]}); };

我知道我必须混淆JSON对象和数组的简单方法,但我似乎无法找到解决方案。

谢谢!

I am trying my best to program an angular app. I have a problem pushing an empty array into an object.

I get an error:

TypeError: Cannot read property 'push' of undefined

I have an object called items which looks like this:

Object { "Name": "name", "Description": "description" }

I would like to push an empty array into the object that can contain another array. Something like this.

Object { "Name": "name", "Description": "description", "Related Items": { Item1:{...}, Item2:{...}, ... } }

My controller does this when it is called:

$scope.push = function () { $scope.item.push({"Related Items":[]}); };

I know I must be getting mixed up with something simple about the JSON Objects and Arrays, but I can't seem to find a solution.

Thankyou!

最满意答案

由于item是一个对象,您只需设置Related Items属性:

$scope.item["Related Items"] = []; $scope.item["Related Items"].push({});

但是,上面看起来像Related Items实际上是一个具有键名称Item1等的对象而不是数组。

$scope.item["Related Items"] = {}; $scope.item["Related Items"].Item1 = {};

Since item is an object, you can just set the Related Items property:

$scope.item["Related Items"] = []; $scope.item["Related Items"].push({});

However, above it looks like Related Items is actually an object with key names Item1, etc. rather than an array.

$scope.item["Related Items"] = {}; $scope.item["Related Items"].Item1 = {};

更多推荐

本文发布于:2023-08-07 15:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464922.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   对象   JSON   Javascript   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!