Javascript 将JSON映射到现有的深层对象结构
假设我有以下类型脚本模型:Javascript 将JSON映射到现有的深层对象结构,javascript,json,typescript,mobx,Javascript,Json,Typescript,Mobx,假设我有以下类型脚本模型: class Person{ public Address: Address; public FirstName: string; public LastName: string; constructor(){ this.Address = new Address(); } } 我通过JSON从服务器获得这个对象的精确表示 我将如何进行常规设置Person和Address的属性,但保持现有对象的完整性
class Person{
public Address: Address;
public FirstName: string;
public LastName: string;
constructor(){
this.Address = new Address();
}
}
我通过JSON从服务器获得这个对象的精确表示
我将如何进行常规设置Person和Address的属性,但保持现有对象的完整性
与此类似,但一般来说:
public SetData(json:any){
this.Address.City = json.Address.City;
this.Address.Province = json.Address.Province;
this.FirstName = json.FirstName;
}
问题是,原始对象必须保留,并且有被称为setter的setter,因为它们是Mobx可观察对象。这排除了Object.assign和我找到的任何“extend”方法
谢谢。在稍微简化的情况下,您可以手动执行,而不需要太多:
它肯定会错过一些检查和角落案例验证,但除此之外,它会满足您的要求。我基于AMIS的最终实现: 从“下划线”中导入*为uu
你试过了吗
extendObservable(这个,json)
SetData中的可能会起作用。这让我走上了正确的道路:)我将在下面发布我的最终解决方案。谢谢
class Address
{
public City: string;
public Province: string;
}
class Person{
public Address: Address;
public FirstName: string;
public LastName: string;
constructor() {
this.Address = new Address();
}
private SetDataInternal(target: any, json: any)
{
if (typeof json === "undefined" || json === null)
{
return;
}
for (let propName of Object.keys(json))
{
const val = target[propName];
if (typeof val === "object")
{
this.SetDataInternal(val, json[propName]);
}
else
{
target[propName] = json[propName];
}
}
}
public SetData(json: any)
{
this.SetDataInternal(this, json);
}
}
const json = {
Address: {
City: "AAA",
Province: "BBB"
},
FirstName: "CCC"
}
const p = new Person();
p.SetData(json);
console.log(p);
export class ObjectMapper
{
public static MapObject(source: any, destination: any) {
_.mapObject(source, (val, key) => {
if(_.isObject(val))
{
this.MapObject(val, destination[key]);
}
else if(_.isArray(val))
{
const array = destination[key];
for(var i in val)
{
const newObject = {};
_.extend(newObject, val[i]);
array.push(newObject);
}
}
else
{
destination[key] = val;
}
});
}
}