Reputation:
I have an JSON object that I am trying to map. SO basically the JSON is like this:
{
"Status": true,
"discounts": {
"broker": {
"discount": "1"
},
"dealer": {
"discount": "0.7"
},
"individual": {
"number_of_cars_discount": {
"1": "1",
"10": "1",
"2": "0.98",
"3": "1",
"4": "1",
}
}
}
}
So I set the post and fetch the data.
const [posts, setPosts] = useState({});
useEffect(() => {
const fetchPosts = async () => {
try {
setLoading(true);
const res = await Axios({
});
if (res.status == 200) {
setPosts(res.data);
}
setLoading(false);
} catch (err) {
setError(err.message);
setLoading(false);
}
};
fetchPosts();
}, []);
So to get the value and display it inside the table here is my code:
<tbody>
<td>
{Object.keys(posts).map((post, index) => (
<tr>
<div key={`broker-${index}`}>{post.discounts}</div>
</tr>
))}
</td>
</tbody>
But unfortunately, I am getting nothing. Thanks for your helps...
Upvotes: 0
Views: 49
Reputation: 1
You can keep posts
as an empty Object
when you do useState()
.
The nested JSON object that you have doesn't work with those cycling you are trying.
If you console.log
the key
in your arrow function inside the map
you would discover that it would be changing value between "Status" and "discounts", so with those keys you cannot access the object inside posts.discounts.broker
because those properties don't exist.
posts.discounts.broker.Status
and posts.discounts.broker.discounts
will always return undefined
.
I think you should consider whether you should flatten your nested JSON
or, if you just need what's inside discounts.broker
, then you can set just that Object
inside of posts
.
Upvotes: 0
Reputation: 85545
Initialize posts
with empty array not boolean value:
const [posts, setPosts] = useState([]);
And you have to map on posts
directly. So, you don't need to use Object.keys()
.
Upvotes: 1