简体   繁体   中英

Angular Typescript Json Cast

I have a problem as I mentioned below.

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. But MiddleName property set undefined in my class. I export to excel that I using the class. Because of MiddleName as null my excel export slipping like below. How can I handle that situtation? How to set default null undefined property?

User Export PS: I am using 'xlsx' library for excel export.

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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