Home > Enterprise >  How to handle the JSON object which lack of some information?
How to handle the JSON object which lack of some information?

Time:10-28

I am using React with nextJS to do web developer,I want to render a list on my web page, the list information comes from the server(I use axios get function to get the information). However some JSON objects are lack of some information like the name, address and so on. My solution is to use a If- else to handle different kind of JSON object. Here is my code:

getPatientList(currentPage).then((res: any) => {
  console.log("Response in ini: " , res);
  //console.log(res[0].resource.name[0].given[0]);
  const data: any = [];
  res.map((patient: any) => {
    if ("name" in patient.resource) {
      let info = {
        id: patient.resource.id,
        //name:"test",
        name: patient.resource.name[0].given[0],
        birthDate: patient.resource.birthDate,
        gender: patient.resource.gender,
      };
      data.push(info);
    } else {
      let info = {
        id: patient.resource.id,
        name: "Unknow",
        //name: patient.resource.name[0].given[0],
        birthDate: patient.resource.birthDate,
        gender: patient.resource.gender,
      };
    data.push(info);
  }
});

Is there any more clever of efficient way to solve this problem? I am new to TS and React

CodePudding user response:

Use the conditional operator instead to alternate between the possible names. You should also return directly from the .map callback instead of pushing to an outside variable.

getPatientList(currentPage).then((res) => {
    const mapped = res.map(({ resource }) => ({
        id: resource.id,
        // want to correct the spelling below?
        name: "name" in resource ? resource.name[0].given[0] : "Unknow",
        birthDate: resource.birthDate,
        gender: resource.gender,
    }));
    // do other stuff with mapped
})
  • Related