开发者

How do I add JSON object as new level to another JSON object?

I have a code that gets in the end collection of two JSON objects, somet开发者_JAVA技巧hing like this.

var jsonL1 = {"holder1": {}}
var jsonL2 = {"section":"0 6","date":"11/12/13"}

I would like to insert jsonL2 inside jsonL1.holder1 and merge it to one JSON object.

Desired output

{
    "holder1": {
        "section": "0 6",
        "date": "11/12/13"
    }
}

How can I do that?


It is as easy as:

L1.holder1 = L2

I removed the "json" from the variable names, as @patrick already said, you are dealing not with "JSON objects" but with object literals.

See also: There is no such thing as a JSON object

You also might want to learn more about objects in JavaScript.


If you want the first object to reference the second, do this:

jsonL1.holder1 = jsonL2;

If you wanted a copy of the second in the first, that's different.

So it depends on what you mean by merge it into one object. Using the code above, changes to jsonL2 will be visible in jsonL1.holder, because they're really just both referencing the same object.


A little off topic, but to give a more visual description of the difference between JSON data and javascript object:

    // this is a javascript object
var obj = {"section":"0 6","date":"11/12/13"};

    // this is valid JSON data
var jsn = '{"section":"0 6","date":"11/12/13"}';
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜