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

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

leamsigc profile image ismael garcia ・1 min read

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

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 
    } 
}

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
    }     
   } 
}

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.

Posted on by:

leamsigc profile

ismael garcia

@leamsigc

Always ask questions to feed the curiosity and learn something new on the way. El respeto al derecho ajeno es la paz. Benito Juarez Garcia.

Discussion

pic
Editor guide