I have an array of objects like this:
"data": [
{
"id": 14,
"banner_type_id": 1,
"name": "banner2022",
},
{
"id": 12,
"banner_type_id": 1,
"name": "banner845",
},
{
"id": 8,
"banner_type_id": 4,
"name": "banner_powertools"
},
]
And these the code:
useEffect(() => {
getData();
}, []);
const getData = () => {
Axios.get(baseUrl)
.then(res => {
console.log('theres: ', res.data.data);
setBanner(res.data.data);
})
}
This result succeed get all-data. But, I just want display the data that only have banner_type_id ==4. What should I do?
2
Answers
If you are looking just to display the element with
banner_type_id === 4
, try usingarray.filter()
.For example, you could create a separate function like
const filtered = banner.filter((x) => x.banner_type_id === 4)
. Then in your return statement you could map over that function like so{filtered.map(x => {return <h1>{x.banner_type_id}</h1>})
. You could check this codesandbox that I created.You can use JavaScript ‘find‘ method to get the data with particular id.