javascript 如何将 JSON 对象作为新级别添加到另一个 JSON 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4808972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 14:56:37  来源:igfitidea点击:

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

javascriptjsonmultidimensional-array

提问by jpkeisala

I have a code that gets in the end collection of two JSON objects, something like this.

我有一个代码,它进入了两个 JSON 对象的最终集合,就像这样。

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.

我想在 jsonL1.holder1 中插入 jsonL2 并将其合并到一个 JSON 对象。

Desired output

期望输出

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

How can I do that?

我怎样才能做到这一点?

采纳答案by Felix Kling

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.

正如@patrick 已经说过的,我从变量名称中删除了“json”,您处理的不是“JSON 对象”,而是对象文字。

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

另请参阅:没有 JSON 对象这样的东西

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

您可能还想了解有关JavaScript 中对象的更多信息。

回答by user113716

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

如果您希望第一个对象引用第二个对象,请执行以下操作:

jsonL1.holder1 = jsonL2;

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

如果您想要第一个中的第二个副本,那就不同了。

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

因此,这取决于您合并为一个对象的含义。使用上面的代码,对 的更改jsonL2将在 中可见jsonL1.holder,因为它们实际上只是引用了同一个对象。



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

有点离题,但为了更直观地描述 JSON 数据和 javascript 对象之间的区别:

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