2017-09-03 47 views
1

说我有以下打字稿型号:地图JSON现有深对象结构

class Person{ 
    public Address: Address; 
    public FirstName: string; 
    public LastName: string; 
    constructor(){ 
     this.Address = new Address(); 
    } 
} 

我得到这个对象的确切表示从通过JSON的服务器。

我将如何去一般设置人员和地址的属性,但保留现有对象完好

所以与此类似,但一般:

public SetData(json:any){ 
    this.Address.City = json.Address.City; 
    this.Address.Province = json.Address.Province; 
    this.FirstName = json.FirstName; 
} 

的疑难杂症是,原来的对象必须保持和有有setter方法被称为他们Mobx观测。这排除了Object.assign和我找到的任何'extend'方法。

谢谢。

+0

你试过[** extendObservable **](https://mobx.js.org/refguide/extend-observable.html)吗? 'SetData'中的'extendObservable(this,json)'可能会起作用。 – Tholle

回答

0

我最后的实现基于Amids:

import * as _ from“underscore”;

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

在一定程度上简化的情况,你可以做手工,没有太多effort

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

它肯定会错过一些检查和极端情况的验证,但除此之外,它确实你问什么。

+0

这使我走上了正确的道路:)我将在下面发布我的最终解决方案。谢谢。 –