Javascript 如何创建和克隆 JSON 对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4120475/
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-08-23 10:59:46  来源:igfitidea点击:

How to create and clone a JSON object?

javascriptjqueryjson

提问by mateusmaso

I was wondering how can I create a JSON (JS) object and then clone it.

我想知道如何创建一个 JSON (JS) 对象然后克隆它。

采纳答案by Felix Kling

How to create a JSON object in javascript/jquery?

如何在 javascript/jquery 中创建一个 JSON 对象?

There is nothing like a JSON object. JSON stands for JavaScript Object Notationand is basically a string that encodes information similar to JavaScript's object literals.

没有什么比 JSON对象更像的了。JSON 代表JavaScript Object Notation,基本上是一个字符串,它对类似于 JavaScript 的对象文字的信息进行编码。

You can however create such an encoding (which would result in a string) with JSON.stringify(object), see JSON in JavaScript. You could also create such a string manually, but it is very error prone and I don't recommend it.

但是,您可以使用 来创建这样的编码(这将产生一个字符串JSON.stringify(object),请参阅JavaScript 中的 JSON。您也可以手动创建这样的字符串,但它很容易出错,我不推荐它。

How do I clone a JSON object in javascript/jquery?

如何在 javascript/jquery 中克隆 JSON 对象?

As it is just a string:

因为它只是一个字符串:

var jsonString2 = jsonString;

I can`t work anymore with javascript arrays

我不能再使用 javascript 数组了

JSON is a format to exchangedata, it is not a data structure you can use in an application.

JSON 是一种交换数据的格式,它不是您可以在应用程序中使用的数据结构。



Maybe you want to read more about JSON, objectsin JS and arraysin JS.

也许你想阅读更多关于JSON、JS 中的对象和 JS 中的数组的内容。

回答by Matías Cánepa

This is what I do and it works like a charm

这就是我所做的,它就像一个魅力

if (typeof JSON.clone !== "function") {
    JSON.clone = function(obj) {
        return JSON.parse(JSON.stringify(obj));
    };
}

回答by Jinex2014

Just do

做就是了

var x = {} //some json object here
var y = JSON.parse(JSON.stringify(x)); //new json object here

回答by Shammoo

As of ES6. Object.assign is a good way to do this.

从 ES6 开始。Object.assign 是一个很好的方法。

newjsonobj = Object.assign({}, jsonobj, {})

The items in the first argument mutate the existing object, and the third argument are changes in the new object returned.

第一个参数中的项目改变了现有对象,第三个参数是返回的新对象的变化。

In ES7 it is proposed that the spread operator be used.

在 ES7 中,建议使用扩展运算符。

newjsonobj = {...jsonobj}

回答by ovunccetin

Q1: How to create a JSON object in javascript/jquery?

Q1如何在 javascript/jquery 中创建一个 JSON 对象?

Creating a Javascript object is so simple:

创建一个 Javascript 对象非常简单:

var user = {}; // creates an empty user object
var user = {firstName:"John", lastName:"Doe"}; // creates a user by initializing 
// its firstName and lastName properties.

After the creation you can add extra fields to your object like user.age = 30;.

创建后,您可以向对象添加额外的字段,例如user.age = 30;.

If you have the object as a JSON string, you can convert it to a JSON object using built-in JSON.parse(yourJsonString)function or jQuery's $.parseJSON(yourJsonString)function.

如果您将对象作为 JSON 字符串,则可以使用内置JSON.parse(yourJsonString)函数或 jQuery 的$.parseJSON(yourJsonString)函数将其转换为 JSON 对象。

Q2: How do I clone a JSON object in javascript/jquery?

问题 2如何在 javascript/jquery 中克隆 JSON 对象?

My way to clone JSON objects is extendfunction of jQuery. For example, you can generate a clone of your user object like below:

我克隆 JSON 对象的方法是扩展jQuery 的功能。例如,您可以生成用户对象的克隆,如下所示:

var cloneUser = $.extend(true, {}, {firstName:"John", lastName:"Doe"});

The first parameter designates whether the clone object will be a shallow or deep copy of the original (see Object copyon wiki).

第一个参数指定克隆对象是原始对象的浅拷贝还是深拷贝(请参阅wiki 上的对象副本)。

To see other JSON cloning alternatives you can read thisarticle.

要查看其他JSON克隆的替代品,你可以阅读文章。

回答by Gabriel Petrovay

This is an issue I have often met when parsing JSON and reusing it several times in the code. And you want to avoid re-parsing every time from the original JSON string, or going the serialize/parseway which is the less efficient way.

这是我在解析 JSON 并在代码中多次重复使用时经常遇到的问题。并且您希望避免每次都从原始 JSON 字符串重新解析,或者serialize/parse采用效率较低的方式。

So in these cases where you want to adjust the parsed object but still keep the original unchanged, use the following function in both server (NodeJs) or client javascript code. The jQuery clonefunction is less efficient because they treat the cases for functions, regexp, etc. The function below, only treats the JSON supported types (null, undefined, number, string, array and object):

因此,在您想要调整解析对象但仍保持原始对象不变的情况下,请在服务器 ( NodeJs) 或客户端 javascript 代码中使用以下函数。jQueryclone函数效率较低,因为它们处理函数、正则表达式等的情况。下面的函数仅处理 JSON 支持的类型(空、未定义、数字、字符串、数组和对象):

function cloneJSON(obj) {
    // basic type deep copy
    if (obj === null || obj === undefined || typeof obj !== 'object')  {
        return obj
    }
    // array deep copy
    if (obj instanceof Array) {
        var cloneA = [];
        for (var i = 0; i < obj.length; ++i) {
            cloneA[i] = cloneJSON(obj[i]);
        }              
        return cloneA;
    }                  
    // object deep copy
    var cloneO = {};   
    for (var i in obj) {
        cloneO[i] = cloneJSON(obj[i]);
    }                  
    return cloneO;
}

回答by kasee nadh reddy bojja

We can clone JSON object as below.

我们可以克隆 JSON 对象,如下所示。

EmployeeDetails = 
{
  Name:"John Deer",
  Age:29,
  Company:"ABC Limited."

}

Now create one clone function

现在创建一个克隆函数

function clonning(Employee)
{
  // conversion from Object to String
  var EmployeeString = JSON.stringify(Employee);

  // conversion from String to Object type

  var EmployeeConvertedObject = JSON.parse(EmployeeString);

  // printing before changing prperty value.

  console.log(EmployeeConvertedObject);

  // modifying EmployeeConvertedObject property value 

  EmployeeConvertedObject.Name="Kelvin Bob";

   // printing After changing prperty value.

  console.log(EmployeeConvertedObject);

  // Now printing original json object.

  console.log(Employee);

  // Here original JSON object is not affecting. Only Cloned object affecting.


}

Now Call function.

现在调用函数。

clonning(EmployeeDetails);

Result:

结果:

clonning(EmployeeDetails)
VM212:22 {Name: "John Deer", Age: 29, Company: "ABC Limited."}
VM212:30 {Name: "Kelvin Bob", Age: 29, Company: "ABC Limited."}
VM212:34 {Name: "John Deer", Age: 29, Company: "ABC Limited."}

回答by praneeth

Let's suppose, We have a JSONOBJECT EmailData which have some Data in it. Now if you want the same data in another object (i.e clone the data) then you can do something like this:

假设,我们有一个 JSONOBJECT EmailData,其中包含一些数据。现在,如果您想在另一个对象中使用相同的数据(即克隆数据),那么您可以执行以下操作:

JSONOBJECT clone_EmailData=new JSONOBJECT(EmailData.toString());

The above statement will give you a new object with the same data and the new object is not a reference to the EmailData object.

上面的语句将为您提供一个具有相同数据的新对象,并且新对象不是对 EmailData 对象的引用。