Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I am having trouble figuring out how to map this JSON correctly in React Native. Do I need to rewrite this json?
This is the json
"rewards" : {
"0" : {
"entries" : 0,
"image" : "url",
"name" : "PlayStation 4 Pro 1TB Console",
"url" : "",
"price" : 399.99
"1" : {
"entries" : 0,
"image" : "url",
"name" : "Xbox One S 500GB",
"url" : "",
"price" : 249.99
{...}
Here is what I tried for mapping
renderItems(){
const{rewards} = this.props;
return rewards.map((data, i) => {
return (<Text> {data[i].name} </Text>)
Yes, you’ll need to rewrite the JSON because map() is expecting rewards to be an array of objects. For example:
"rewards": [{
"entries" : 0,
"image" : "url",
"name" : "PlayStation 4 Pro 1TB Console",
"url" : "",
"price" : 399.99
"entries" : 0,
"image" : "url",
"name" : "Xbox One S 500GB",
"url" : "",
"price" : 249.99
You’ll also want to use JSON.parse on the rewards prop if you’re not already. Here is an example of how you might use JSON.parse when rendering the component with the rewards prop:
render() {
const rewardsJSON = '{"rewards":[{"entries":0,"image":"url","name":"PlayStation 4 Pro 1TB Console","url":"","price":399.99},{"entries":0,"image":"url","name":"Xbox One S 500GB","url":"","price":249.99}]}';
return (
<YOUR_COMPONENT
rewards=JSON.parse(rewardsJSON).rewards
–
–
.map()
should be called on an array. rewards
is not an array here, so a solution would be to convert it to an array first.
Suppose your json is this:
const myJson =
"rewards" : {
"0" : {
"entries" : 0,
"image" : "url",
"name" : "PlayStation 4 Pro 1TB Console",
"url" : "",
"price" : 399.99
"1" : {
"entries" : 0,
"image" : "url",
"name" : "Xbox One S 500GB",
"url" : "",
"price" : 249.99
You can dynamically convert it (with any length) to an array:
let index = 0
let dataArr = []
while (myJson.rewards[index]) {
arr.push(myJson.rewards[index])
index++
hopping the above code is clear enough...
So now the dataArr
contains your data like:
dataArr = [{
"entries" : 0,
"image" : "url",
"name" : "PlayStation 4 Pro 1TB Console",
"url" : "",
"price" : 399.99
"entries" : 0,
"image" : "url",
"name" : "Xbox One S 500GB",
"url" : "",
"price" : 249.99
And finally it's the time to map it as you want:
return dataArr.map((data, i) => (<Text key={i}> {data.name} </Text>))
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.