在javascript中将对象追加到子对象

时间:2014-04-12 07:29:10

标签: javascript jquery

我有以下对象:

var dpsets = {
    "routes": [
        {
            "name": "first",
            "values": [
                "info",
                "more info",
                "text"
            ]
        },
        {
            "name": "second",
            "values": [
                "text again",
                "with info"

            ]
        }
    ]
}

我还有以下对象:

var currentSet = {
    "name": "New Route",
    "values": [
        "Latest one",
        "Latest two"
    ]
}

我正在尝试将currentSet附加到routes的{​​{1}}元素。

我已尝试dpsets和jQuery' dpsets.routes.push(currentSet),但似乎都没有按照我的要求行事。

最好的方法是什么?

4 个答案:

答案 0 :(得分:0)

尝试 -

dpsets.routes.push((currentSet));

alert(JSON.stringify(dpsets));

fiddle

答案 1 :(得分:0)

最初这不起作用:

dpsets.routes.push(currentSet)

然而,在再次尝试之后,它运作良好。

答案 2 :(得分:0)

var dpsets = {
"routes": [
    {
        "name": "first",
        "values": [
            "info",
            "more info",
            "text"
        ]
    },
    {
        "name": "second",
        "values": [
            "text again",
            "with info"

        ]
    }
]
};
var currentSet = {
    "name": "New Route",
    "values": [
        "Latest one",
        "Latest two"
    ]
};

dpsets.routes.push(currentSet);
console.log(dpsets);

Demo

答案 3 :(得分:-1)

您是否尝试使用方法concat()?

dpsets.concat(currentSet)