Home > other >  check if multiples values exists in React
check if multiples values exists in React

Time:05-07

I have the foloowing data from an api

 obj = {
  firstName: "John",
  lastName : "Doe",
  job      :null
  id       : 5566,
};

i want to check if the value is not empty in the obj before rendering I tried

render() {
  return (
   <div>
   obj.firstName && <p>{obj.firstName}</p>
   </div>
          );
}

it works fine but i will have multiple duplicated code if i'm gonna check every value(firstName/lastName/job etc ...) also i need to put firstName and LastName in one line <p>{obj.firstName} - {obj.lastName}</p> how can i make the check in a efficient way.

CodePudding user response:

This is not a react question, it's a javascript question.

You can check using the in operator

render() {
  return (
   <div>
   "firstName" in obj && "lastName" in obj && <p>{obj.firstName}</p>
   </div>
);
}

CodePudding user response:

If all of them have the same printing pattern, you can try to loop through keys for value check before adding to JSX

render() {
  return (
   <div>
   {Object.keys(obj).map((objKey) => obj[objKey] ? <p>{obj[key]}</p> : null)}
   </div>
   );
}

For {obj.firstName} - {obj.lastName}, you can add getter to obj (as your previous question)

obj = {
  firstName: "John",
  lastName : "Doe",
  job      :null
  id       : 5566,
  get name() {
     //if one of firstName and lastName is not available, return an empty value as no name
     if(!firstName || !lastName) {
         return ''
     }
     return `${this.firstName} - ${this.lastName}`
  }
}; 

Object.keys will go through name for you as well, so you can re-use the same above map.

  • Related