skip to Main Content

I’m trying to access both keys and also values in an array of an API

export default const App= () =>{

    const [data, setData] = useState([]);
    console.log(data);

     //Some fetch code here
    //setData happen here
  
    return  (
       <View >
        <Text >fetched data</Text>
          <Text>{data?.data?.a}</Text>
          <Text>{data?.data?.b}</Text>
          <Text>{data?.data?.c}</Text>

        </View>
        )

};

the supposed array is like this

arr = {code: 0, data:{a: 1, b: 2, c: 3}}

but it will only return 1, 2, 3 and I wanted it to be a: 1, b: 2, c: 3

2

Answers


  1. You can access the Object.entries

    const arr = {code: 0, data:{a: 1, b: 2, c: 3}}
    
    console.log(`<Text>${Object.entries(arr.data).map(([key,val])=>`${key}:${val}`).join('</Text></Text>')}</Text>`)
    Login or Signup to reply.
  2. Try this

    <View>
        <Text>fetched data</Text>
        {Object.entries(arr?.data).map(([key, val]) => {
            <Text>{`${key}:${val}`}</Text>;
        })}
    </View>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search