2

i have testdata.js file with json test data as below:

testdata.js file:

module.exports = 

{ createHost: {

        name : "System-001",
        description: "Creating System",

    }

}

In another test, I am trying to create a variable called testcase1 with the above test data. Changing the property value in testcase1, changes the value in the testdata.js file json object.

it("Create a host", function(){
var testcase1 = testdata.createHost;

testcase1.name="sys-002";

console.log(testcase1.name);
console.log(testdata.createHost.name);
});

Response: sys-002 sys-002

My requirement is to create a copy of testdata instead of creating a reference. How can I do this?

4 Answers4

7

Shortest way:

var copied = JSON.parse(JSON.stringify(object));
Azamantes
  • 1,435
  • 10
  • 15
0

You can use a for in loop to loop through each of the properties and assign them by value.

var createHost = { name : "System-001", description: "Creating System" }
var test = {};
for (var key in createHost)
 test[key] = createHost[key];
  
test.name = "Test";

console.log(test.name);
console.log(createHost.name);
entropic
  • 1,683
  • 14
  • 27
0

You can use the extend function in jQuery to clone the object:

var testCaseClone = jQuery.extend({}, testdata);
ux11
  • 158
  • 2
  • 13
0

There's no such thing as "JSON object" (unless you literally mean global object that holds parse and stringify functions). There are only JSON strings. As such you copy them using simple = operator.

var copy_json_string = original_json_string

If you need to copy an object instead (it is object, just object, not "JSON object"), there are dozens of answers already, for example at: How do I correctly clone a JavaScript object?.

Community
  • 1
  • 1
Oleg V. Volkov
  • 21,719
  • 4
  • 44
  • 68