-
-
Save mppfiles/85c7609d9eeb74e4b6e02f1b91157162 to your computer and use it in GitHub Desktop.
Angular copy objects example
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
Ejemplo de cómo transformar una estructura de datos en instancias de objetos (copiando propiedades + métodos). |
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 { Component } from '@angular/core'; | |
import { Person } from './Person'; | |
import { Pet } from './Pet'; | |
@Component({ | |
selector: 'example', | |
templateUrl: './example.component.html', | |
styleUrls: ['./example.component.css'] | |
}) | |
export class ExampleComponent { | |
testing() { | |
const raw_data = [ | |
{ pet_name: 'Ollie', owner: { name: 'John Doe' } }, | |
{ pet_name: 'Bob', owner: { name: 'Marcus Doe' } }, | |
]; | |
const all_pets: Pet[] = new Pet().fromList(raw_data); | |
console.dir(all_pets); | |
} | |
} |
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
export abstract class Model { | |
fromList(src: any, extra?: any) { | |
const res = []; | |
for (const item of src) { | |
res.push(this.fromObject(Object.assign(item, extra))); | |
} | |
return res; | |
} | |
fromObject(src: any) { | |
const obj = Object.create(this); | |
return Object.assign(obj, src); | |
} | |
} |
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 { Model } from './Model'; | |
export class Person extends Model { | |
name: String = null; | |
} |
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 { Model } from './Model'; | |
import { Person } from './Person'; | |
export class Pet extends Model { | |
pet_name: String = null; | |
owner: Person = null; | |
fromObject(src) { | |
src = super.fromObject(src); | |
src.owner = new Person().fromObject(src.person); | |
return src; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment