1

In my TypeScript program, I have an array which looks like the following:

array = [
  {
    id,
    ...
    nested: [
      {
        id,
        ..
      },
      {
        id,
        ..
      }
    ]
  },
  ...
]

I need to create a copy of this array, but all methods I've found online (including this thread only seem to work with an array of objects and not the nested kind here (as the nested array is also operated upon). Whilst JSON.parse(JSON.stringify(array)) could have worked, I have a date property in the object which must be preserved.

What can I do?

EDIT: Not sure why this has been marked as duplicate, but I specifically make reference to the fact that that thread does not work in this case.

Paul Clavier
  • 291
  • 4
  • 13

3 Answers3

1

Have you tried lodash.cloneDeep()? https://lodash.com/docs/4.17.5#cloneDeep

Rob
  • 242
  • 3
  • 7
1

If You're allowed to use external libraries, take a look at _.cloneDeep(value) in lodash library. The code should look as follows:

// Original array
const originalArray = [
  {
    id,
    ...
    nested: [
      {
        id,
        ..
      },
      {
        id,
        ..
      }
    ]
  },
  ...
];

// Cloned array
const clonedArray = lodash.cloneDeep(originalArray);

It should solve the problem.

Dariusz Sikorski
  • 4,309
  • 5
  • 27
  • 44
0

You can use this

function extend( a, b ) {
        for( var key in b ) { 
            if( b.hasOwnProperty( key ) ) {
                a[key] = b[key];
            }
        }
        return a;
    }

copyarray = extend( {}, copyarray);
extend( copyarray, array);
yasir jafar
  • 167
  • 1
  • 9