Search code examples
arraysnode.jspointersreferenceclone

How to copy a array in node without reference and JSON parse/stringify


I want to copy a global static array to individualise the array to each user session.

I tryed to copy that array with concat/slice/[...array] but it takes every time the same reference / pointer. Only with JSON.parse(JSON.stringify(array)) it seems to work.

Is there a more efficient way to copy a array / object / variable without geting the reference / pointer with it

var Array2 = [...Array];

var Array2 = Array.concat();

var Array2 = Array.slice();

dosent work.

var Array = [{
   test: 'i am a test'
}]


var Array2 = Array;

Array2.favorite = true;

console.log(Array) //result: test: 'i am a test', favorite: true

var Array3 = JSON.parse(JSON.stringify(Array)); 

console.log(Array) //result: test: 'i am a test'

Solution

  • What you trying to do is - clone the array content. So you have few options:

    1. Use lodash
      • var newArr = _.cloneDeep(originalArr)
    2. If you are sure, you have just simple objects - you may use something like:
      • var newArr = originalArr.map(d => Object.assign({}, d))
    3. In case the structure is well known - you may write cloneFunction for the structure, than use your own clone with originalArr.map(cloneFunction)