简体   繁体   English

Angular Typescript Json 演员表

[英]Angular Typescript Json Cast

I have a problem as I mentioned below.我有一个问题,如下所述。

API: API:

 "Data": [
  {
    "Id": 90110,        
    "Name": "John",
    "Surname": "Doe",       
    "Email": "johndoe@gmail.com",    
    "Status": "Active"
  },
  {
    "Id": 90109,
    "Name": "Sally",
    "Surname": "Doe",        
    "Email": "sallydoe@gmail.com",  
    "MiddleName":"II",           
    "Status": "Active"
  }]

As you can see above.正如你在上面看到的。 Nullable property don't reach me.可以为空的财产没有联系到我。 I parsed that JSON to my typescript class.我将 JSON 解析为我的 typescript class。 But MiddleName property set undefined in my class.但是在我的 class 中未定义 MiddleName 属性。 I export to excel that I using the class.我使用 class 导出到 excel。 Because of MiddleName as null my excel export slipping like below.由于 MiddleName 为 null 我的 excel 出口下滑,如下所示。 How can I handle that situtation?我该如何处理这种情况? How to set default null undefined property?如何设置默认 null 未定义属性?

User Export PS: I am using 'xlsx' library for excel export.用户导出PS:我正在使用“xlsx”库进行 excel 导出。

You say that you "parsed that JSON to my typescript class", but you don't show the code for that class, or the parsing code, so we can't debug that for you.您说您“将 JSON 解析为我的 typescript 类”,但是您没有显示该 class 的代码或解析代码,因此我们可以为您调试。

However, assuming that you have defined a class that has properties that exactly match the JSON, and assuming that you want an empty string when a property is missing from the JSON, you could do something like this with the result from your API request: However, assuming that you have defined a class that has properties that exactly match the JSON, and assuming that you want an empty string when a property is missing from the JSON, you could do something like this with the result from your API request:

const data = apiJson.map( (person) => {
    Object.assign(
       new Person(), 
       {
         Id: person.Id,
         Name: person.Name || '',
         Surname: person.Surname || '' ,        
         Email: person.Email || '',  
         MiddleName: person.MiddleName || '',           
         Status: person.Status || ''
       }
    )
});

If your class has no methods, you should probably make it an interface instead, and omit the construction of the object and the Object.assign(), as in:如果您的 class 没有方法,您可能应该将其设为接口,并省略 object 和 Object.assign() 的构造,如下所示:

const data = apiJson.map( (person) => {
       return {
         Id: person.Id,
         Name: person.Name || '',
         Surname: person.Surname || '' ,        
         Email: person.Email || '',  
         MiddleName: person.MiddleName || '',           
         Status: person.Status || ''
       }
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM