简体   繁体   English

如何创建和克隆一个 JSON object?

[英]How to create and clone a JSON object?

I was wondering how can I create a JSON (JS) object and then clone it.我想知道如何创建一个 JSON (JS) object 然后克隆它。

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));
    };
}

Just do做就是了

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

As of ES6.从 ES6 开始。 Object.assign is a good way to do this. 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}

This is an issue I have often met when parsing JSON and reusing it several times in the code.这是我在解析 JSON 并在代码中多次重复使用时经常遇到的问题。 And you want to avoid re-parsing every time from the original JSON string, or going the serialize/parse way which is the less efficient way.并且您希望避免每次都从原始 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.因此,在您想要调整解析对象但仍保持原始对象不变的情况下,请在服务器 ( NodeJs ) 或客户端 javascript 代码中使用以下函数。 The jQuery clone function 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): jQuery clone函数效率较低,因为它们处理函数、regexp 等的情况。下面的函数仅处理 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;
}

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 extend function of jQuery.我克隆 JSON 对象的方法是扩展jQuery 的功能。 For example, you can generate a clone of your user object like below:例如,您可以生成用户对象的克隆,如下所示:

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 copy on wiki).第一个参数指定克隆对象是原始对象的浅拷贝还是深拷贝(请参阅 wiki 上的对象副本)。

To see other JSON cloning alternatives you can read this article.要查看其他JSON克隆的替代品,你可以阅读文章。

How to create a JSON object in javascript/jquery?如何在 javascript/jquery 中创建一个 JSON 对象?

There is nothing like a JSON object .没有什么比 JSON对象更像的了。 JSON stands for JavaScript Object Notation and is basically a string that encodes information similar to JavaScript's object literals. 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 .但是,您可以使用JSON.stringify(object)创建这样的编码(这将产生一个string JSON.stringify(object) ,请参阅JavaScript 中的 JSON You could also create such a string manually, but it is very error prone and I don't recommend it.您也可以手动创建这样的字符串,但它很容易出错,我不推荐它。

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 exchange data, it is not a data structure you can use in an application. JSON 是一种交换数据的格式,它不是您可以在应用程序中使用的数据结构。


Maybe you want to read more about JSON , objects in JS and arrays in JS.也许你想阅读更多关于JSON 、JS 中的对象和 JS 中的数组的内容。

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."}

Let's suppose, We have a JSONOBJECT EmailData which have some Data in it.假设,我们有一个 JSONOBJECT EmailData,其中包含一些数据。 Now if you want the same data in another object (ie clone the data) then you can do something like this:现在,如果您想在另一个对象中使用相同的数据(即克隆数据),那么您可以执行以下操作:

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 对象的引用。

var aa = { n : 1 }
var bb = { ...aa } // bb is a copy of aa by val not by ref, changing bb will not affect aa, and changing aa will not affect bb

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM