mateusmaso
mateusmaso

Reputation: 8453

How to create and clone a JSON object?

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

Upvotes: 51

Views: 126163

Answers (9)

oncode
oncode

Reputation: 1163

Modern solution for deep cloning object without converting nested objects like Dates into strings:

structuredClone(object)

MDN Docs: https://developer.mozilla.org/en-US/docs/Web/API/structuredClone

Upvotes: 2

kasee nadh reddy bojja
kasee nadh reddy bojja

Reputation: 126

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

Upvotes: 1

praneeth
praneeth

Reputation: 21

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.

Upvotes: 0

Shammoo
Shammoo

Reputation: 1103

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}

Upvotes: 24

Matías Cánepa
Matías Cánepa

Reputation: 5974

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

Upvotes: 64

Jinex2014
Jinex2014

Reputation: 342

Just do

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

Upvotes: 28

ovunccetin
ovunccetin

Reputation: 8663

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.

Upvotes: 7

Gabriel Petrovay
Gabriel Petrovay

Reputation: 21884

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

Upvotes: 13

Felix Kling
Felix Kling

Reputation: 816472

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.

Upvotes: 5

Related Questions