0

I have created a JavaScript object like below -

var objtvar = {defaultPoints: [[0,0],[0,-10],[2.5, -10], [2.5, -10],[5, -10],[5,0]]}

I need to assign the defaultPoints property to another array and modify this new array. However on updating this new array, the object property too gets updated.

I want the object property to not change.

Code -

var objtvar = {defaultPoints: [[0,0],[0,-10],[2.5, -10], [2.5, -10],[5, -10],[5,0]]};
var flag = objtvar.defaultPoints;
flag[5][1] = 9;

This updates the values in both flag array and the defaultPoints property. I do not wish the property to get updated.

Updated Solution - We can use the jquery extend suggested by @Nimrod Shory or use a pure JS implementation like this http://heyjavascript.com/4-creative-ways-to-clone-objects/

Manya
  • 315
  • 4
  • 17
  • http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript – Suraj Rao Jan 18 '17 at 13:47
  • Actually this is about cloning an array, and the question does not mention jQuery. The solution is changing line 2 to: `var flag = objtvar.defaultPoints.slice(0);` – Tudor Ilisoi Jan 18 '17 at 14:17
  • @TudorIlisoi That's actually wrong because this is an array of arrays and because an array is a reference type it will change the old object. – Nimrod Shory Jan 18 '17 at 14:36
  • indeed, it needs recursion. Mea culpa – Tudor Ilisoi Jan 18 '17 at 14:37

1 Answers1

0

You have to deep clone the object if you don't want to assign a reference. You can do that with jQuery:

var flag = jQuery.extend(true, {}, objtvar).defaultPoints;

var objtvar = {defaultPoints: [[0,0],[0,-10],[2.5, -10], [2.5, -10],[5, -10],[5,0]]};
var flag = jQuery.extend(true, {}, objtvar).defaultPoints;

flag[0][1] = 3;

$('#objtvar').text('objtvar[0][1] = ' + JSON.stringify(objtvar.defaultPoints[0][1]));
$('#result').text('flag[0][1] = ' + JSON.stringify(flag[0][1]));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="objtvar"></div>
<div id="result"></div>
Nimrod Shory
  • 2,475
  • 2
  • 19
  • 25
  • This creates an object in which the array gets split into individual properties. Tried removing property 'defaultPoints' from the extend command, This does clone but the issue persists. The original objects gets updated on assignment. – Manya Jan 18 '17 at 14:07
  • @Manya - Edited my answer – Nimrod Shory Jan 18 '17 at 14:27
  • is there a Javascript equivalent? I am using this code in Protractor UI tests which is based out of node js and the last thing I want to do is include jquery npm package – Manya Jan 18 '17 at 16:57
  • 1
    Got the answer - http://heyjavascript.com/4-creative-ways-to-clone-objects/ – Manya Jan 18 '17 at 17:45