I am having trouble finding an appropriate title for the issue I am currently facing. Therefore, I will provide a detailed explanation of the problem.
I have a class named Model.ts
export class Model{
a:ObjA;
b:ObjB;
c:ObjC;
d:string;
e:boolean;
constructor(){
this.a = new ObjA();
this.b = new ObjB();
this.c = new ObjC();
}
}
The subclasses are simplified for the purpose of this question
ObjA.ts
export class ObjA{
propA:string;
propB:ObjD;
constructor(){
this.propB = new ObjD();
}
}
ObjB.ts
export class ObjB{
propA:string;
propB:number;
}
ObjC.ts
export class ObjC{
propA:string;
propB:number;
}
Now, from a service, I receive the following JSON
{a:{propA:"some val"},c:{propB:12},d:"blah"}
My objective is to be able to assign the JSON to the class Model
in such a way that I achieve this result
{a:{propA:"some val",propB:{}},b:{},c:{propB:12},d:"blah"}
When using Object.assign(new Model(),json)
, the output I get is
{a:{propA:"some val"},c:{propB:12},d:"blah"}
Notice the absence of
b
here. Also,a
does not includepropB
Therefore, my question is, How can I map the JSON in such a way that if any property, which is an object, is missing in the JSON, an empty object will be created? (I am willing to use lodash and similar utilities)
P.S: The scenario here is that I am developing an Angular2 application in which the properties are entered using a form. If I use the elvis operator in HTML (obj?.prop), the value for that property is never set because the object does not have that property. If I do not use the elvis operator, then the age-old undefined
is returned.
Sample form:
...
<input [(ngModel)]="model.a.propA"/>
<input [(ngModel)]="model.a.propB"/>
<input [(ngModel)]="model.b.propA"/>
<input [(ngModel)]="model.b.propB"/>
.
.
.
...
Related *.ts component
class Component implements OnInit{
....
model:Model = new Model();
ngOnInit(){
getData().subscribe(res=>Object.assign(model,res));
}
}