【问题标题】:Map JSON to existing deep object structure将 JSON 映射到现有的深层对象结构
【发布时间】:2017-09-05 04:14:02
【问题描述】:

假设我有以下 Typescript 模型:

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

问题在于原始对象必须保留,并且因为它们是 Mobx 可观察对象而调用了 setter。这排除了 Object.assign 和我找到的任何“扩展”方法。

谢谢。

【问题讨论】:

  • 你试过extendObservable吗? SetData 中的 extendObservable(this, json) 可能会起作用。

标签: javascript json typescript mobx


【解决方案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);

它肯定会遗漏一些检查和极端情况验证,但除此之外,它会满足您的要求。

【讨论】:

  • 这让我走上了正确的道路:) 我将在下面发布我的最终解决方案。谢谢。
【解决方案2】:

我基于 Amids 的最终实现:

从“下划线”导入*为_;

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

【讨论】:

    猜你喜欢
    • 2015-06-27
    • 2018-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-12
    • 2019-05-27
    • 1970-01-01
    相关资源
    最近更新 更多