Reputation: 339
I m having problems when I try to map a json into my react component and I don t know by..
this is the structure:
{
"cards": [
{
"id": "1",
"fares": [
{
"fareRef": "1",
"prices": {
"afterTax": 100
}
}
],
"international": false,
},
{
"id": "2",
"fares": [
{
"fareRef": "1",
"prices": {
"afterTax": 200
}
}
],
"international": false,
},
]
}
and inside my component I m doing this:
cards.map(element => (
<p>{element.id}</p> // works!
<p>{element.fares.map(element => element.prices)}</p> // dosen 't work..
))
Thanks!
Upvotes: 0
Views: 69
Reputation: 1111
You are getting that error because you are creating a new array of objects from element.fares that looks like [ { afterTax: 100 }, { afterTax: 200 }]
. React can't render those objects so it spits out that error. If you want to see the fares, try something like:
cards.map(element => (
<p>{element.id}</p>
<p>{element.fares.map(element => element.prices.afterTax)}</p>
))
Obviously you'll have to format it because this will literally result in 100200 but gives you an idea of what's wrong.
Upvotes: 0
Reputation: 1432
cards.map(card => (
<p>{card.id}</p>
<p>{card.fares.map(fare => fare.prices)}</p>
))
In general, you should avoid using generic variable names like element
to label the items of an iterable to avoid name clashes like this.
Also, did you mean to render an object? Because fare.prices
is an object. Did you mean to render fare.prices.afterTax
instead? If that's the case, then it should be:
cards.map(card => (
<p>{card.id}</p>
<p>{card.fares.map(fare => fare.prices.afterTax)}</p>
))
Upvotes: 0
Reputation: 5763
That's because element.fares.prices
in your 2nd map call comes out to be:
"prices": {
"afterTax": 100
}
You're rendering an object, which is not allowed. Try element.fares.prices.afterTax
.
cards.map(card => (
<p>{card.id}</p> // works!
<p>{card.fares.map(fare => fare.prices.afterTax)}</p> // dosen 't work..
))
Upvotes: 1
Reputation: 42516
I am not sure what is the desired behaviour, but right now, you are trying to render an object (element.prices
) as part of the <p>
element. Assuming you are trying to display the afterTax
values, you should be referencing the afterTax
property within prices
.
cards.map(element => (
<p>{element.id}</p> // works!
<p>{element.fares.map(element => element.prices.afterTax)}</p>
))
Upvotes: 2