【发布时间】:2013-06-14 00:54:24
【问题描述】:
所以我有一些我正在使用的现有 Javascript。这是正在运行的现有 JSON(经过修改和简化以保持可管理性):
{
"items": [
{
"id": "11",
"type": "subType",
"attributesList": {
"atribute1": "1",
"atribute2": "2"
},
"description": {
"d1": "lorem ipsum",
"d2": {
"lorem ipsum 1": "li1 content",
"lorem ipsum 2": "li2 content"
}
}
}
]
}
针对此现有 JSON 的操作之一是添加一个新的“项目”,如下所示:
{
"id": "12",
"type": "subType",
"attributesList": {
"atribute1": "1",
"atribute2": "2"
},
"description": {
"d1": "lorem ipsum",
"d2": {
"lorem ipsum 1": "li1 content",
"lorem ipsum 2": "li2 content"
}
}
}
执行这一切的代码非常冗长,但这是执行操作的那一行:
that.product.addItem(item.toObject());
所以,这很好用。但是,我们还有另一种 JSON 格式需要以相同的方式进行修改。新格式是:
{
"items": [
{
"id": "1",
"type": "someType",
"name": "item name",
"items": [
{
"id": "11",
"type": "subType",
"attributesList": {
"atribute1": "1 attr",
"atribute2": "2 attr"
},
"description": {
"d1": "lorem ipsum",
"d2": {
"lorem ipsum1": "li1 content",
"lorem ipsum 2": "li2 content"
}
}
},
{
"id": "12",
"type": "subType",
"attributesList": {
"atribute1": "1 attr",
"atribute2": "2 attr"
},
"description": {
"d1": "lorem ipsum",
"d2": {
"lorem ipsum1": "li1 content",
"lorem ipsum 2": "li2 content"
}
}
}
],
"quantity": 1
}
]
}
如您所见,子类型现在嵌套在父类型下。所以我的想法是,要向这种新格式添加一个项目,我应该能够执行以下操作(因为只有一个父级):
that.product.items[0].items.addItem(item.toObject());
但是,当我尝试这样做时,我得到了一个 TypeError:
TypeError: that.product.items[0].items.addItem is not a function
当我在两者上都获得 typeof 时,它们都返回“object”,但显然我错过了一些东西。我对像这样操作 JSON 很陌生,所以我很难过。我走了几条转换路径并试图弄清楚这一点,但我只是卡住了。希望有人能帮帮我。
【问题讨论】:
-
我不确定
addItem是什么,因为我从未见过这种方法。但是如果你只是想追加到一个数组,你应该可以使用push()方法来代替。
标签: javascript json object typeerror