1

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?

raosaeedali
  • 113
  • 8

1 Answers1

-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
  • 2
    If 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
  • 2
    You further want to run `new_obj` through `JSON.parse` after `JSON.stringify` – Dexygen Nov 21 '17 at 12:44
  • The first one only creates a shallow copy. – JLRishe Nov 21 '17 at 12:45
  • @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
  • @Sandeep does slice() works for multi-dimensional array too? – raosaeedali Nov 21 '17 at 12:53
  • @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
  • @Sandeep alright and thanks btw. :) – raosaeedali Nov 21 '17 at 12:56