Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle object and Array in react native?

Am actively creating a react native app for my college studies ! In that am using external api as data source. The problem am facing is that sometimes am getting data in single object and sometimes its in array format. How to handle this in react native perspective ?

As am maping jsx considering it as array but when i get object it throws error

My data example:

const data = {         // this is example of single object 
   entry: {
      key: "0",
      value: "Patrik"
   }
}

const data = {         // this is example of array
   entry: [
   {
      key: "0",
      value: "Patrik"
   },
    {
      key: "1",
      value: "John"
   }],
}

So this is how i get data from external api, and now my react native jsx code:

     { data.entry.map(o => {
               <View key={o.key}>
                      <View style={{ paddingLeft: 25 }}>
                            <Text style={{ fontWeight: 'bold' }}>{o.value}</Text>
                      </View>
                  </View>

                }) 
      }

So, when i get array, it works but when i get object this throws error ! Any help on this ?

like image 844
PatriciaD19 Avatar asked Dec 21 '20 05:12

PatriciaD19


People also ask

How do you handle an array of objects in React?

To render an array of objects in react with JSX we need to use Array. map() to transform the object into something react can make use of because you cannot directly render an object into React. Instead, by using Array.

How do you use an array in react native?

To create and use an array in react native, just use square brackets [] it will create an array like the below example.


Video Answer


2 Answers

You should do Array.isArray(data.entry) to check if you have an array of object or a single object. And perform the logic based on that.

like image 67
Sagar Shakya Avatar answered Oct 30 '22 04:10

Sagar Shakya


Convert Object to Array so you won't get error.

if(!Array.isArray(data.entry)){
  data = { entry: [data.entry] };
}

like image 40
JustRaman Avatar answered Oct 30 '22 04:10

JustRaman