Deep copy an array in Angular 2 + TypeScript

前端 未结 10 1139
温柔的废话
温柔的废话 2020-11-27 04:33

I have an array of objects that is an input. Lets call it content.

When trying to deep copy it, it still has a reference to the previous array.

10条回答
  •  我在风中等你
    2020-11-27 05:23

    A clean way of deep copying objects having nested objects inside is by using lodash's cloneDeep method.

    For Angular, you can do it like this:

    Install lodash with yarn add lodash or npm install lodash.

    In your component, import cloneDeep and use it:

    import * as cloneDeep from 'lodash/cloneDeep';
    ...
    clonedObject = cloneDeep(originalObject);
    

    It's only 18kb added to your build, well worth for the benefits.

    I've also written an article here, if you need more insight on why using lodash's cloneDeep.

提交回复
热议问题