Copying of an array of objects to another Array without object reference in javascript(Deep copy)

后端 未结 7 530
说谎
说谎 2020-12-01 05:05

I have a scenario where i need to copy the array of Objects(Main array) to another Temp array which should not have object reference basically if i make any modification to

7条回答
  •  感情败类
    2020-12-01 05:32

    To copy the values of an array without copying the reference of the array, you can simply do:

    let tempArray = [...mainArray];
    

    This is the recommended solution for AirBnb's JS Style Guide: https://github.com/airbnb/javascript#arrays

    However, this will not create new referenes for the objects inside the array. To create a new reference for the array and the objects inside, you can do:

    JSON.parse(JSON.stringify(mainArray));
    

提交回复
热议问题