0

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

1
  • That's not an array. {data.data && Object.entries(data.data).map((key, value) => <Text key={key}>{key}: {value}</Text>)} (also: const [data, setData] = useState({});) reactjs.org/docs/lists-and-keys.html Commented Aug 30, 2022 at 6:03

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

Try this

<View>
    <Text>fetched data</Text>
    {Object.entries(arr?.data).map(([key, val]) => {
        <Text>{`${key}:${val}`}</Text>;
    })}
</View>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.