开发者

How to create and clone a JSON object?

开发者 https://www.devze.com 2023-01-24 10:24 出处:网络
I was wondering how can I create a JSON (JS) object开发者_StackOverflow社区 and then clone it.This is what I do and it works like a charm

I was wondering how can I create a JSON (JS) object开发者_StackOverflow社区 and then clone it.


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. Object.assign is a good way to do this.

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.

newjsonobj = {...jsonobj}


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/parse way which is the less efficient way.

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 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):

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?

Creating a Javascript object is so simple:

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;.

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.

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

My way to clone JSON objects is extend function of 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).

To see other JSON cloning alternatives you can read this article.


How to create a JSON object in javascript/jquery?

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

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.

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

As it is just a string:

var jsonString2 = jsonString;

I can`t work anymore with javascript arrays

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


Maybe you want to read more about JSON, objects in JS and arrays in JS.


We can clone JSON object as below.

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. Now if you want the same data in another object (i.e 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.

0

精彩评论

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

关注公众号