1

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'
1
  • 1
    There are a number of ways to perform a deep copy of an object in javascript, but believe me, the most widely used is JSON.parse(JSON.stringify(Array)). What are your concerns with that method? Realistically, if your concerns are with performance, you shouldn't be performing regular deep copies of objects period. Commented Oct 4, 2019 at 19:35

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.