2017-09-03 88 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

這使我走上了正確的道路:)我將在下面發佈我的最終解決方案。謝謝。 –