Home > Enterprise >  How to map an array of objects in React Native
How to map an array of objects in React Native

Time:03-23

How to map an array of objects in React Native

Api response data

Object {
  "data": Object {
    "1": Object {
      "fk_i_attribute_id": "1",
      "fk_i_item_id": "60730",
      "locales": Object {
        "en_US": "Car Make",
      },
      "pk_i_id": "12368",
      "s_name": "Car Make",
      "values": Object {
        "355": Object {
          "hierarchy": Object {
            "355": Object {
              "locales": Object {
                "en_US": "Others Brands",
              },
              "pk_i_id": "355",
              "s_name": "Others Brands",
            },
          },
          "locales": Object {
            "en_US": "Others Brands",
          },
          "pk_i_id": "355",
          "s_name": "Others Brands",
        },
      },
    },
    "2": Object {
      "fk_i_attribute_id": "2",
      "values": Array [
        Object {
          "hierarchy": Array [],
          "locales": Array [],
          "pk_i_id": 0,
          "s_name": "",
          "s_value": "0",
        },
      ],
    },

Now I am trying to map through this data to display it on my screen:

{ data?.map(function (item, index) { return ( {item.s_name} ); }) }

But getting nothing

CodePudding user response:

data should be an array , which in your case is an object. Keep in mind map function only works with array and not with objects.

function App (){

   // assume data is an array which you are getting from some api
   return <View>
            { data?.map(function (item, index) { return ( 
              <Text key={index} >
               {item.s_name}
              </Text> 
              )})
            }
          </View>
   }

CodePudding user response:

 [
    {
        name: 'Sam',
        email: '[email protected]'
    },

    {
        name: 'Ash',
        email: '[email protected]'
    }
].map((anObjectMapped, index) => {
    return (
        <p key={`${anObjectMapped.name}_{anObjectMapped.email}`}>
            {anObjectMapped.name} - {anObjectMapped.email}
        </p>
    );
})
  • Related