简体   繁体   English

克隆对象数组,其中包含另一个对象数组

[英]Clone an array of objects which contains another array of objects

In my TypeScript program, I have an array which looks like the following: 在我的TypeScript程序中,我有一个如下所示的数组:

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. 我需要创建这个数组的一个副本,但所有的方法,我在网上找到(包括此线程似乎只与对象的数组,而不是那种嵌套在这里(如嵌套数组也对其进行操作的工作)。虽然JSON.parse(JSON.stringify(array)) 可以工作,我在对象中有一个必须保留的date属性。

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. 编辑:不确定为什么将其标记为重复,但是我特别提到了在这种情况下该线程不起作用的事实。

Have you tried lodash.cloneDeep() ? 您是否尝试过lodash.cloneDeep() https://lodash.com/docs/4.17.5#cloneDeep https://lodash.com/docs/4.17.5#cloneDeep

If You're allowed to use external libraries, take a look at _.cloneDeep(value) in lodash library. 如果允许使用外部库,请查看lodash库中的_.cloneDeep(value) 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. 它应该解决问题。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM