Last active
July 6, 2022 14:46
-
-
Save nameofSEOKWONHONG/2488a01129b8f9745419afd67ac25145 to your computer and use it in GitHub Desktop.
typescript mapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { AsyncHook } from "async_hooks"; | |
import { Person } from "./user"; | |
export class Mapper { | |
constructor() { | |
} | |
static mapped<T, T2>(src:T, type:{new():T2}):T2 { | |
const srcNames = Object.getOwnPropertyNames(src); | |
const destObj = new type(); | |
srcNames.forEach((v, i) => { | |
destObj[v] = src[v]; | |
}); | |
return destObj; | |
} | |
static mapped2(src:any, mappedObject:any, parentKey:string = '') { | |
Object.keys(src).forEach((key) => { | |
if(typeof src[key] === 'object') { | |
if(isEmpty(mappedObject[key]) === true) { | |
mappedObject[key] = {}; | |
} | |
this.mapped2(src[key], mappedObject[key], key); | |
} | |
else { | |
mappedObject[key.toLowerCase()] = src[key]; | |
} | |
}); | |
} | |
} | |
function isEmpty(obj: any): boolean { | |
if(obj == null || obj == undefined) return true; | |
if(Object.keys(obj).length === 0) return true; | |
return false; | |
} | |
export class User { | |
id:number; | |
name:string; | |
// constructor(id:number, name:string){ | |
// this.id = id; | |
// this.name = name; | |
// } | |
} | |
export class UserSub { | |
name:string; | |
age:number; | |
person:Person | |
constructor(name:string = '', age:number = 0, person:Person = null) { | |
this.name = name; | |
this.age = age; | |
this.person = person; | |
} | |
} | |
export class Person { | |
sex:string; | |
constructor(sex:string ='') { | |
this.sex = sex; | |
} | |
// constructor(user:User){ | |
// this.user = user; | |
// } | |
} | |
export class TestUser { | |
public id:number; | |
public name:string; | |
public age:number; | |
public user:UserSub; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment