How can an array value or an object be copied to another variable without copying its reference in Javascript so that the copied value and variable can be manipulated independently, without causing any change to the original one?
Asked
Active
Viewed 57 times
1
-
For arrays, you can do `array.slice(0);` – Rajesh Nov 21 '17 at 12:41
-
You need to deep clone the object. Also show your attempt as well by using `<>`. – gurvinder372 Nov 21 '17 at 12:41
-
Did you mean [this](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)? – Mikhail Katrin Nov 21 '17 at 12:41
-
You can refer this link for deep copy: https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript – Rajesh Nov 21 '17 at 13:35
1 Answers
-2
Array coping by value:
var array = [1,2,3];
var newArr = array.slice();
and Object coping by value:
var obj = {name : "A"};
var new_obj = JSON.stringify(obj);

Sandeep
- 1,461
- 13
- 26
-
2If this is the correct answer, we should look for similar posts and mark it as duplicate. Also, `json.stringify` will remove functions – Rajesh Nov 21 '17 at 12:43
-
2You further want to run `new_obj` through `JSON.parse` after `JSON.stringify` – Dexygen Nov 21 '17 at 12:44
-
-
@Rajesh I know JSON.stringify remove functions. but I think u not read the question. :- LOL – Sandeep Nov 21 '17 at 12:49
-
@Sandeep First, please mind the tone. Second, any data in question is a sample data. Actual data is always more complex. Third, when you answer, make sure you answer in a way you cover obvious issues. – Rajesh Nov 21 '17 at 12:52
-
-
@raosaeedali No. inner objects will again be assigned using reference. Instead of asking a generic question, my suggestion is to put a specific one with proper use-case. – Rajesh Nov 21 '17 at 12:54
-