jpkeisala
jpkeisala

Reputation: 8906

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, something 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?

Upvotes: 9

Views: 23944

Answers (2)

user113716
user113716

Reputation: 322452

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"}';

Upvotes: 4

Felix Kling
Felix Kling

Reputation: 816262

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.

Upvotes: 8

Related Questions