Home > Software design >  How to filter items in array by region?
How to filter items in array by region?

Time:08-24

So I'm getting incidents reports from Google Cloud API and displaying it. I'm trying to only display the ones that are happening on the US. As you can see, the raw data from the API is like this:

enter image description here

I want to filter it, so I only get the ones that have us on it, how can I do it? This is the code now:

export const getGoogleStatus = async () => {
    const response = await axios.get('https://status.cloud.google.com/incidents.json')
    console.log('Raw Data: ', response.data)
    const status = response.data.map((e) => {
        return {
            name: e.affected_products.map((e) => {
                return e.title
            }),
            status: e.most_recent_update.status,
            location: e.most_recent_update.affected_locations.map((e) => {
                return e.title
            }),
        }
    })
    return status
}

CodePudding user response:

You can use filter method in order to filter elements that doesn't match a specific criteria. Since you want only the items that are in the US, therefore you can check if it includes its code using include, which I believe it will be (us- as a substring.

export const getGoogleStatus = async () => {
    const response = await axios.get('https://status.cloud.google.com/incidents.json')
    console.log('Raw Data: ', response.data)
    const status = response.data.map((e) => {
        return {
            name: e.affected_products.map((e) => {
                return e.title
            }),
            status: e.most_recent_update.status,
            location: e.most_recent_update.affected_locations.map((e) => {
                return e.title
            }).filter((e)=>e.includes('(us-')), //filters all elements that doesn't include '(us-' as a substring
        }
    })
    return status
}

CodePudding user response:

That seems like a static JSON file so you can use filter() to check if the location contains (us- as shown below:

location: e.most_recent_update.affected_locations.map((e) => {
  return e.title
}).filter((r) => r.includes("(us-"))

If you want affected_products in US, then you can use the same filter on e.affected_products itself and check if affected_locations has any location from US.

  • Related