It maybe basic, but i'm stuck of how to display JSON file in react native For example, i'm get a json object by
const [post, setPost] = React.useState(null);
const baseURL = 'https://jsonplaceholder.typicode.com/posts/1';
React.useEffect(() => {
axios.get(baseURL).then(response => {
console.log(response.data);
setPost(response.data);
});
}, []);
And it return like
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Now i want to display on screen something like
1
1,
sunt aut facere repellat provident occaecati excepturi optio reprehenderit,
quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto
I know, i can use post.userId or post.id to display each of them, but if i have 1000 items like this, how can i display them without call keys?
i tried
{Object.keys(post).map(i => (
<Text>{i}</Text>
))}
But it return something like
{
"userId"
"id"
"title"
"body"
}
So how can I display data instead of key without using key?
You can use Object.values to get the enumerable property values and Array.join to join the resulting array into a string:
const obj = {
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
const res = Object.values(obj).join('\n')
console.log(res)
Your Object.keys approach is also fine - you'll just need to get the value of the property:
const obj = {
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
const res = Object.keys(obj).map(i => obj[i]).join('\n')
console.log(res)