0

I copy the object and change the property,

it seems the property has been change, but the object not change:

var partCp = myDoorObj['part'][0];
for (var i = 0; i < doorCount; i++) {

    partCp['var']['no'] = i + 1;
    partCp['var']['_name'] = 'door' + (i + 1);

    console.log(partCp);
    console.log(partCp['var']['_name']);

    myDoorObj['part'].push(partCp);

}

with the console log:

enter image description here

partCp['var']['_name'] has been change, but partCp object in the console are same..

so whats the problem??

chanjianyi
  • 607
  • 4
  • 15
  • 35
  • `=` copies the reference only. Did you mean to make a deep copy? You possibly need some recursion to do that, underscore.js provides a suitable deepcopy. – Paul May 29 '14 at 08:00
  • @chanjianyi If you don't get an answer then just thank Juhana. – Dropout May 29 '14 at 08:02
  • Juhanas point is that there is a known bug where you can't trust th e console to log objects as they were. Also, though, the OP says he copies an object when only the reference is copied. – Paul May 29 '14 at 08:04

2 Answers2

0

You are pushing the same object twice. JavaScript arrays store objects by reference; both of them now refer to the same object. However, you are also using a browser that suffers from a bug that the objects written to console.log are not displayed until after a while, and thus the value shown there is not the value of the object upon the time of console.log but some point of time afterwards.

However, your code is still buggy.

partCp refers here to the same object all the time; you first change that object's number to 1 and name to door1, then push; and after that you change the same object's number to 2 and name to door2, and push a reference to that object again; as there was only 1 object to begin with, both elements of the array are references to the same object. Now, the browser bug made you post a question, but on a working browser, if you do console.log(myDoorObj['part']) you would see that there still are door2s in the array.

To construct a new copy of the partCp, see Javascript - How to clone an object?

Community
  • 1
  • 1
  • But the object is sent to the console *before* it's changed. The issue is with how Chrome queues messages sent to the console, not with object properties. – JJJ May 29 '14 at 07:59
0

I find a way to solve the problem...

var partCp = jQuery.extend(true, {}, myDoorObj['part'][0]);

for (var i = 0; i < doorCount; i++) {

    var tempPartCp = jQuery.extend(true, {}, partCp);

    tempPartCp['var']['no'] = i + 1;
    tempPartCp['var']['_name'] = 'door' + (i + 1);

    console.log(tempPartCp);
    console.log(tempPartCp['var']['_name']);

    myDoorObj['part'].push(tempPartCp);

}
chanjianyi
  • 607
  • 4
  • 15
  • 35