angular2: how to copy object into another object

后端 未结 8 671
失恋的感觉
失恋的感觉 2021-01-30 10:05

Please help me in order to copy the object into another object using angular 2?

In angular, I used angular.copy() to copy objects to the loose reference of the old object

相关标签:
8条回答
  • 2021-01-30 10:29

    Object.assign will only work in single level of object reference.

    To do a copy in any depth use as below:

    let x = {'a':'a','b':{'c':'c'}};
    let y = JSON.parse(JSON.stringify(x));
    

    If want to use any library instead then go with the loadash.js library.

    0 讨论(0)
  • 2021-01-30 10:33

    As suggested before, the 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.

    0 讨论(0)
  • 2021-01-30 10:38

    Try this.

    Copy an Array :

    const myCopiedArray  = Object.assign([], myArray);
    

    Copy an object :

    const myCopiedObject = Object.assign({}, myObject);
    
    0 讨论(0)
  • 2021-01-30 10:39

    Solution

    Angular2 developed on the ground of modern technologies like TypeScript and ES6.

    So you can just do let copy = Object.assign({}, myObject).

    Object assign - nice examples.

    For nested objects : let copy = JSON.parse(JSON.stringify(myObject))

    0 讨论(0)
  • 2021-01-30 10:39
    let course = {
      name: 'Angular',
    };
    
    let newCourse= Object.assign({}, course);
    
    newCourse.name= 'React';
    
    console.log(course.name); // writes Angular
    console.log(newCourse.name); // writes React
    

    For Nested Object we can use of 3rd party libraries, for deep copying objects. In case of lodash, use _.cloneDeep()

    let newCourse= _.cloneDeep(course);
    
    0 讨论(0)
  • 2021-01-30 10:42
    let copy = Object.assign({}, myObject).  as mentioned above
    

    but this wont work for nested objects. SO an alternative would be

    let copy =JSON.parse(JSON.stringify(myObject))
    
    0 讨论(0)
提交回复
热议问题