ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Thursday, October 27, 2022

[FIXED] How to handle the JSON object which lack of some information?

 October 27, 2022     javascript, reactjs   

Issue

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


Solution

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


Answered By - CertainPerformance
Answer Checked By - - Timothy Miller (ReactFix Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix