'How to iterate through array inside objects which is inside main object
I have an API: https://www.gov.uk/bank-holidays.json
It contains an object, which contains 3 keys (Division) whose value is also an object and it includes an array showing holiday Details (events). I want to print the "title" and 'date' from it for each Division. Below is the code. How to render the data for title and date inside the Holiday.js?
export default function App() {
const [data, setData] = useState([]);
const fetApi = () => {
fetch("https://www.gov.uk/bank-holidays.json")
.then((res) => res.json())
.then((items) => setData(items));
};
useEffect(() => {
fetApi();
}, []);
return (
<div className="App">
<Holidays data={Object.entries(data)} />
</div>
);
}
/ / Holiday.js
const Holidays = ({ data }) => {
// console.log(data);
return (
<div>
<ol>
{data.map((item, i) => {
return (
<li key= {i}>
<div>title:</div> //render title here
<div>Date :</div> //render date here
</li>
);
})}
</ol>
</div>
);
};
this is Sandbox link : enter link description here
Solution 1:[1]
Change Holliday Element into: (explanation on comments)
const Holidays = ({ data }) => {
// console.log(data);
return (
<div>
<ol className="App">
{data.map((item, i) => {
// since you are passing Object.entries, the first parameter is the key
// and the second one are the values
const [key, obj] = item;
// you then just have to map the event inside the values
return obj.events.map((o, index) => (
<li key={index}>
<div>title: {o.title}</div>
<div>Date : {(o.date)}</div>
</li>
));
})}
</ol>
</div>
);
};
Solution 2:[2]
replace your Holiday comonent with this
const Holidays = ({ data }) => {
const ListItem = (array) => {
console.log(array);
return array[1].events.map((item, i) => {
return (
<li key={i}>
<div>title: {item.title}</div>
<div>Date :{item.date}</div>
</li>
);
});
};
return (
<div>
<ol>{data.map((array) => ListItem(array))}</ol>
</div>
);
};
export default Holidays;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | I am L |
| Solution 2 | Muhammad Raheel |
