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

后端 未结 7 525
说谎
说谎 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:51

    For some other people with the same question. You could also do it this way.
    Using the new es6 features you could create a copy of an array (without reference) and a copy of every object without one level of references.

    const copy = array.map(object => ({ ...object }))
    

    It's much more functional and idiomatic IMHO

    Note: Spread syntax effectively goes one level deep while copying an array. Therefore, it may be unsuitable for copying multidimensional arrays as the following example shows (it's the same with Object.assign() and spread syntax).
    More info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

    So basically if your objects doesn't have objects as properties. This syntax is everything you need. Unfortunately there is not "out of the box" deep clone feature on the spec but you can always use a library if that's what you need

    Browser Compatibility Warning: I think it is part of the specification of Ecma now, but some browsers doesn't have full support of spread syntax jet. But using one of the popular transpilers out there you will be fine

提交回复
热议问题