Reputation:
I'm trying to display the data from my local JSON file in React. Here is how I see the data from the console: JSON data in the console. The structure is Data -> Classes -> Class[0-730] -> Term (or any other).
So if I try to print the Term of Class[0] in the console, I would do
console.log(Data.Classes.Class[0].Term)
and get the desired result. However, when I try to display the same data in the website, I get the following error:
Cannot read property '0' of undefined
Here is how my code looks like:
return Data.Classes ? (
<ul>
{Object.keys(Data.Classes).map((item, idx) => {
return item ? (
<li key={idx}>
<h3>{item.Class[idx] ? item.Class[idx] : "Doesn't exist"}</h3>
</li>
) : null;
})}
</ul>
): null;
};
I assume there is something going wrong after mapping that makes item.Class[idx] undefined, but I am not sure why. Is there something I am missing?
Upvotes: 0
Views: 66
Reputation: 1176
idx is the index of the item, so it doesn't make sense to use the index of the parent item lower in the depth.
Since you're called the map on Object.keys(Data.Classes)
, you're mapping the keys from a list of strings, so it will look like this: ["key1", "key2"..]
.
As I see it, you likely want this:
{Data.Classes.Class.map((item, idx) => {
return (
<li key={idx}>
<h3>{item.Term} - {item.Dept} - {item.Course} - {item.Section}</h3>
</li>
);
})}
I'm not sure why you have ternary operators. Specific keys might be null, but Map will only go to items on the list, so item will never be null. It might be empty (like {}
or ''
) but not null.
Upvotes: 1