[英]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對象和數組的簡單知識感到困惑,但是我似乎找不到解決方案。
謝謝!
由於item
是對象,因此只需設置Related Items
屬性即可:
$scope.item["Related Items"] = [];
$scope.item["Related Items"].push({});
但是,在上方看來,“ Related Items
實際上是鍵名稱為Item1
等的對象,而不是數組。
$scope.item["Related Items"] = {};
$scope.item["Related Items"].Item1 = {};
JavaScript的push
函數僅在將值推入數組時才起作用。 如果您嘗試推入一個對象,它將不起作用,而是嘗試調用不存在的“推”鍵。 這就是為什么您遇到錯誤的原因。
確保$scope.item
是一個數組( []
或new Array
),然后使用您想要的值將其推送到該new Array
。
$scope.item = [];
$scope.push = function () {
$scope.item.push({"Related Items":[]});
};
這是 W3School的.push()方法說明。
項目對象應類似於{....“ Related Items”:<“ some value”> ....}
它應該已經有密鑰。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.