将JSON数组写入对象

时间:2013-06-28 23:51:52

标签: javascript arrays json object replacewith

我有一些看起来像这样的JSON。

[
{
    "items": [
        {
            "id": "xxxx",
            "description": {
                "style": "",
                "specs": ""
            }
        },
        {
            "id": "xxxx",
            "description": {
                "style": "",
                "specs": ""
            }
        }
    ],
    "category": "xxxxxx",
    "name": "xxxxxx"
},
{
    "items": [
        {
            "id": "xxxx",
            "description": {
                "style": "",
                "specs": ""
            }
        },
        {
            "id": "xxxx",
            "description": {
                "style": "",
                "specs": ""
            }
        }
    ],
    "category": "xxxxxx",
    "name": "xxxxxx"
}
]

它被传递给我作为'newItem'。并且正在我正在处理的现有代码中设置两次:

that.cart.addItem(newItem.toObject());

后来:

that.origCart.replaceWith(that.cart);

传统上,当'items'是一个平面列表时,它工作得很好。但是,上面的JSON是新的JSON格式,因此我需要为每个类别/名称传递“项目”。

在'for'循环中我输出了我需要的东西。(我需要将它们分开。)

newItem.items

但是,当我尝试执行以下操作时,我遇到了类型错误。 (是的,一旦我开始工作,我将会有多个'推车'。)

that.cart.addItem(newItem.items.toObject());

TypeError: newItem.items.toObject is not a function

如何才能将'newItem.items'设置为正确的类型,或者我可以替换哪些操作来正确设置?我在网上找到了很多没有成功的东西,现在我转向专家。只是不是我的强项(还)。

1 个答案:

答案 0 :(得分:1)

看起来你正试图从newItems对象调用items函数,即使items是一个Array。请尝试以下方法:

that.cart.addItem(newItem.items);