I am having trouble filtering the json that I have in React Typescript Using Hooks. I have a JSON that comes from a fetch and it looks like this:
[
{
"dealer 1":
[
{
"name": "SERVICE 1"
"city": "NORTH CANTON"
"phone": "3306596372"
"isOpen": "true"
},
{
"name": "SERVICE 2"
"city": "OHIO"
"phone": "3306596372"
"isOpen": "true"
}
]
},
{
"dealer 2":
[
{
"name": "SERVICE A"
"city": "WASHINGTON"
"phone": "3306596375"
"isOpen": "true"
},
{
"name": "SERVICE B"
"city": "SEATTLE"
"phone": "3306596376"
"isOpen": "true"
}
]
}
]
my code for fetching the api is:
useEffect(() => {
axios.get("API URL here")
.then(res => {
console.log(res)
setCTSN(res.data)
});
}, []);
and I wanted to return all open dealers so I need to filter it by "isOpen=true"
const isOpen = 'true'
const result = OPEN
.map(item => ({
...item, //Spread types may only be created from object types.ts(2698)
children: item.children
.filter(child => child.value.includes(isOpen.toLowerCase()))
}))
.filter(item => item.children.length > 0)
console.log(result)
but I am getting an error with the '...item' and I'm not sure if I am doing it correctly in React Typescript.
Can someone help me?
You can do it this way
OPEN.filter(item => item[Object.keys(item)[0]].some(service => service.isOpen))
But IMHO you have a problem with the json data, it doesn't looks like a good modelling.
This structure would be better, and thus filtering easier:
{
name: "dealer 1",
services:
[
{
"name": "SERVICE 1"
"city": "NORTH CANTON"
"phone": "3306596372"
"isOpen": "true"
},
{
"name": "SERVICE 2"
"city": "OHIO"
"phone": "3306596372"
"isOpen": "true"
}
]
}
and then filter like this...
OPEN.filter(item => item.services.some(service => service.isOpen))
You should make ur OPEN
array with this method then use map for showing them on react.
if u have trouble with showing them, ask me for code on comment.
const Json = [ { "dealer 1": [ { "name": "SERVICE 1", "city": "NORTH CANTON", "phone": "3306596372", "isOpen": true }, { "name": "SERVICE 2", "city": "OHIO", "phone": "3306596372", "isOpen": false } ] }, { "dealer 2": [ { "name": "SERVICE A", "city": "WASHINGTON", "phone": "3306596375", "isOpen": true }, { "name": "SERVICE B", "city": "SEATTLE", "phone": "3306596376", "isOpen": true } ] } ] const OPEN = [] Json.forEach(item => { OPEN.push({ dealer:Object.keys(item)[0], service:item[Object.keys(item)[0]].filter(service =>service.isOpen) }) }) console.log(OPEN)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.