-3

I'm making a small example to display JSON (key and value). When I copy the JSON to another variable, I've tried to delete key Age and re-displayed the first JSON. Key Age in the first JSONhas been deleted, too.

$('button').click(function () {
  var json = {};
  json['Name'] = 'Hermione';
  json['Age'] = 19;
  
  for (i in json) {
    $('body').append($('<p>').text(i + ': ' + json[i]))
  }
   
  var copy = json;
  delete copy['Age'];
  
  for (i in json) {
    $('body').append($('<p>').text(i + ': ' + json[i]))
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click me</button>

So, my question is: Copying an object to another object means nothing in JavaScript, right?

I think that because when I copied it, it's still operating on the main version (json), not on the copy version (copy).

TarkaDaal
  • 18,798
  • 7
  • 34
  • 51
Tân
  • 1
  • 15
  • 56
  • 102
  • You're not copying the object when you do copy = json. You're just creating another reference to the same object. – João Paulo Macedo Jan 15 '16 at 12:50
  • Why are you referring to your objects as "JSON", which is a string-based format for exchanging information between eg server and client? –  Jan 15 '16 at 14:11

6 Answers6

1

var copy = json; will create a reference of the json object.

Javascript objects are mutable, it means if you remove property from one object then another object referring that object will also lose that key.

If you do not want that to happen then look for deep copy of javascript objects which will create new independent objects.

Rayon
  • 36,219
  • 4
  • 49
  • 76
1

Thats because you simply assigned the same object to another variable. If you really want to copy the object you could use the extend function of jquery.

// Shallow copy
var copy = jQuery.extend({}, json);

// Deep copy
var copy= jQuery.extend(true, {}, json);

See this thread for deeper information about "cloning" js objects.

Community
  • 1
  • 1
Douglas Gardim
  • 420
  • 1
  • 4
  • 11
1

your var copy = json is a reference to json, not a copy of json. It is simply a pointer to the same place in the memory. So whenever you say delete copy["Age"], you are refering to json["Age"]

Thomas
  • 111
  • 8
1

you cannot simply copy objects to another variable like var copy = json; because objects are assigned by reference.

try,

var copy = JSON.parse(JSON.stringify(json));
Azad
  • 5,144
  • 4
  • 28
  • 56
  • Of the many ways to deep-clone an object, that is certainly one, but by no means the best one. See related questions. –  Jan 15 '16 at 14:15
1

var copy = json; simply creates a new variable called "copy" (a pointer), which points to the object "json". You haven't "copied" anything. You are simply saying I am going to give json another name, and the name is "copy". If you want to recursively clone an object, you'll need to write a function that does it or use underscore/lodash's _.cloneDeep().

var objects = [{ 'a': 1 }, { 'b': 2 }];

var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
// → false
Henry Zou
  • 1,809
  • 1
  • 14
  • 19
-1

Its Working

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script>
        function myFunction() {
            var json = {};
            json['Name'] = 'Hermione';
            json['Age'] = 19;
            for (i in json) {
                $('body').append($('<p>').text(i + ': ' + json[i]))
            }
            var copy = json;
            delete copy['Age'];
            for (i in json) {
                $('body').append($('<p>').text(i + ': ' + json[i]))
            }
        }
    </script>
</head>
<body>
    <input type="button" class="button" onclick="myFunction()" value="Click me"> 
</body>