DEV Community

Cover image for 🔥🔥🔥 Copying object keys and values to a class.🔥🔥🔥
Ismael Garcia
Ismael Garcia

Posted on

🔥🔥🔥 Copying object keys and values to a class.🔥🔥🔥

Coping the values of and object parameter to this in a class

  • At first I declare the type and default values for my class keys, but then I realize that I will need to set the values in the constructor again. So the first solution that I thought of was the fallowing:
//typescript
export default class Project {
    id: string = "";
    name: string = "";
    date_end: string = "";
    description: string = "";
    parent: number | null = null;
    //....MORE keys

    constructor(data?: any) {
         let self = this;
        if (data) {
            Object.getOwnPropertyNames(data).forEach(key =>{
              self[key] = data[key].value
            })
        }
    } 
}
Enter fullscreen mode Exit fullscreen mode

But this solution it seems to dirty and crazy so i try the fallowing :

export default class Project {
    id: string = "";
    name: string = "";
    date_end: string = "";
    description: string = "";
    parent: number | null = null;
    //....MORE keys

    constructor(data?: any)
        if (data) {
            Object.assign(this, data);
        }cover_image: direct_url_to_image.jpg 
    } 
}
Enter fullscreen mode Exit fullscreen mode

So what is Object.assing(target,source) doing ?

  • Only copies enumerable and own properties from a source object to a target object.
  • It uses [[Get]] on the source and [[Set]] on the target.
  • It assigns properties versus just copying or defining new properties.

The other option for me would be doing, the fallowing :

export default class Project {
constructor(data?: any){
   if (data) {
    this.id: string = data.id;
    this.name: string = data.name;
    this.date_end: string = data.date_end;
    this.description: string = data.description;
    this.parent: number | null = data.parent;
    //....MORE keys
    }     
   } 
}
Enter fullscreen mode Exit fullscreen mode

Please any opinion or suggestions, about this topic or what is the best or a better implementation of assigning key -> values from obj1 to obj2, are more than welcome.

Top comments (0)