Suppose I call an API using Axios to bring back an object that contains an array of objects and each object contains the following info:
{id: some_ID, name: some_Name, class:some_class}
Normally I would save the data returned from an API call in a variable then I would do the filter and save the results in another data structure. Is there a way to filter the returned object returned by Axios by the className before saving the result?
This is not a problem of Axios it’s a question of the API. Normally you should be able to tell the API to return only data you need but we cannot help as long as we do not know what API you are using and what data you want to fetch
1 Like
Yeah just requesting the filtered data would be most efficient, but if this not possible you can still filter()
the results manually (which isn’t specific to Axios either BTW but a builtin array method):
const response = await axios.get('https://my-api-url')
const result = response.data.filter(item => item.class === 'something')
// Save result to file or something...
Hi m3g4p0p, What you are showing me is what I normally do. I would values returned by the API call save it to a variable then filter the values in that variable. What I want to do instead is filter the values returned from the API call then save it to a variable that way I’m not wasting memory space and time.
1 Like
When the result is coming from the API it is in the memory. Doesn’t matter if you store it into a variable or not. The only way to reduce memory usage is what I say: do not request unused data from the API
2 Likes
You can filter the results directly in the .then()
function or within an async/await
structure right after the API call and before saving it.
Using .then()
const axios = require('axios');
axios.get('YOUR_API_ENDPOINT')
.then(response => {
const filteredData = response.data.filter(item => item.class === 'desired_className');
// Now you can save filteredData or use it directly.
console.log(filteredData);
})
.catch(error => {
console.error('Error fetching data:', error);
});
And using async/await
const axios = require('axios');
async function fetchData() {
try {
const response = await axios.get('YOUR_API_ENDPOINT');
const filteredData = response.data.filter(item => item.class === 'desired_className');
// Now you can save filteredData or use it directly.
console.log(filteredData);
} catch (error) {
console.error('Error fetching data:', error);
}
}
fetchData();
Your code does exactly the same like in answer #3. except is uses then instead of await. But the response is also in memory and assigned to response before you filter it.