FIlter a dictionary array in JavaScript - javascript

I'm using a feth request to recieve data from an API.
This is what my request looks like:
fetch(url, requestOptions)
.then(response => response.json())
.catch(error => colsole.log('error', error);
And I'm trying to figure out how to filter certain values from the response.
Here's what the response looks like:
[
{
'Obj.Name': 'objname1',
'Obj.property': 'red'
...
},
{
'Obj.Name': 'objname1',
'Obj.property': 'blue'
...
},
{
'Obj.Name': 'objname3',
'Obj.property': 'green'
...
},
]
I wanna add another ".then" statement there with a function that gets a parameter like ('Obj.Name') that can filter everything by that particular objectname and be able to get other properties of that object.
I want the result to be something like this:
Obj: objectname1, ObjProp: red

Like this?
fetch(url, requestOptions)
.then(response => response.json())
.then((data) => {
const filtered = data.filter(item => item["Obj.Name"] === "objname1")
console.log(filtered)
})
.catch(error => colsole.log('error', error);

Related

Get Cart Id from JSON response

I need to capture the cartID in a js variable from a JSON response.
So far I have the following code which requests the cart information.
function getCart(url) {
return fetch(url, {
method: "GET",
credentials: "same-origin"
})
.then(response => response.json())
};
var cartID = 'unknown';
getCart('/api/storefront/carts')
.then(data => console.log(JSON.stringify(data)))
.catch(error => console.error(error));
The console.log data is formatted like this:
Extract of full data:
[{"id":"c5f24d63-cd9a-46f2-be41-6ad31fc38b51","customerId":1,"email":"me#gmail.com", ................. }]
I have tried various methods to capture the cart ID to variable cartID, but each time it shows 'unknown' and is logged before the data response.
Any ideas how to delay until the response is ready and then 'cartID' with the id value?
Because the response if a JSON array, you can try to loop and extract the cartID from each cart object:
function getCart(url) {
return fetch(url, {
method: "GET",
credentials: "same-origin"
})
.then(response => response.json())
};
var cartID = 'unknown';
getCart('/api/storefront/carts')
.then(
data => {
//The response is an array of cart objects. We need to extract the ID from the array
cartID = data[0].id;
//Or loop through the response and extract the ID from each cart object
for (var i = 0; i < data.length; i++) {
cartID = data[i].id;
}
}
)
.catch(error => console.error(error));

Get response.data from fetch() as variable to use in React-Native

I've seen several posts about this, so I apologize if it's a direct duplicate. The examples I've seen have the RN components built with classes. I'm using functions, and I'm new, so it's all very confusing.
const getFlights = async () => {
const token = await getAsyncData("token");
instance({
method: "get",
url: "/api/flights/",
headers: {
Authorization: `Token ${token}`,
},
})
.then(function (response) {
// console.log(response.data.results); // shows an array of JSON objects
return response.data.results; // I've also tried response.data.results.json()
})```
I just want the response returned as a variable that I can use to populate a FlatList component in RN.
const FlightListScreen = () => {
const [list, setList] = useState([]);
const flights = getFlights(); // currently returns as a promise object
Thank you for your help.
I think you have to store the response object directly to the json method. And then with that response you can store it to the variable
.then(response => { return response.json() })
.then(response => {
this.setState({
list: response
})
you are sending token without a bearer. Concrete your token with bearer like this
headers: {
Authorization: "Bearer " + token,
},
and another thing is your response class are not right this should be like this
.then((response) => response.json())
.then((responseJson) => {
API will Resopne here....
}
this is a complete example to call API with Token
fetch("/api/flights/", {
method: "GET",
headers: {
Authorization: "Bearer " + token,
},
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
setState(responseJson.VAlue);
})
.catch((error) => {
alert(error);
});

Multiple API Calls in React

I am making an app where I receive data from an API. Once I get this data I want to make another call to the same API with the endpoint that I got from the first call.
fetch(req)
.then((response)=>(
response.json()
)).then((json)=>{
console.log(json)
json.meals.map((obj)=>{
let url = `https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/${obj.id}/information`
let req = new Request(url,{
method: 'GET',
headers: header
})
fetch(req)
.then((response)=>(
response.json()
)).then((json)=>{
console.log(json);
this.setState((prevState)=>{
recipe: prevState.recipe.push(json)
})
})
})
this.setState(()=>{
return{
data: json
}
})
})
I am making two fetch requests here but the problem is the data from the first response is output after second fetch request. Also the state: data gets set before state: recipe and the components render with the data from state: data.
render(){
return(
<div className="my-container">
<EnterCalorie getData={this.getData}/>
<MealData data={this.state.data} recipe={this.state.recipe}/>
</div>
)
}
How can i make sure both get passed down at the same time?
In line 3 return return response.json() instead of nothing (undefined).
Update:
const toJson = response => response.json()
fetch(req)
.then(toJson)
.then(json => {
this.setState(() => {
return {
data: json
}
})
return json
})
.then((json) => {
console.log(json)
const promises = json.meals.map((obj) => {
let url = `https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/${obj.id}/information`
let req = new Request(url, {
method: 'GET',
headers: header
})
return fetch(req)
.then(toJson)
.then((json) => {
console.log(json);
this.setState((prevState) => ({
recipe: prevState.recipe.push(json)
}))
})
})
return Promise.all(promises)
})
.then(() => {
console.log('job done')
})
You need to map your array into promises. Then use Promise.all to wait for them the get resolved.
There was parenthesis missing from:
this.setState((prevState)=>{
recipe: prevState.recipe.push(json)
})
A sidenote, this whole stuff should be refactored. You're not going to get far with this code style / code complexity.
fetch(req) // req no1
.then((response)=>(
response.json()
)).then((json)=>{
console.log(json)
json.meals.map((obj)=>{
let url = `https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/${obj.id}/information`
let req = new Request(url,{
method: 'GET',
headers: header
})
fetch(req) // req no 1 called again
.then((response)=>(
response.json()
)).then((json1)=>{
console.log(json1);
this.setState((prevState)=>{
recipe: prevState.recipe.push(json1)
})
this.setState(()=>{
return{
data: json
})
})
})
})
})
I think you are calling api with same req parameters again in the second fetch call
This is a callback hell, please look for Promise races, and check the all() promise method.

Why response.data is undefined?

I am fetching data using an API in react native. When fetched data in console, its successfully getting data. But while using the code below, the album array is showing undefined.
state = { albums: [] };
componentWillMount() {
//fetch('https://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&api_key=881262b246e1d3f2abda8771b1a25fe3&format=json')
fetch('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => this.setState({ albums: response.data }));
}
I am getting console logs like this
{albums: Array(0)}
{albums: undefined}
Why this is undefined?
A Response object has no data property. You access the body of the response by calling the text, json, blob, or arrayBuffer methods and consuming the promise they return.
For instance, if you're receiving JSON:
fetch('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => response.json())
.then(data => this.setState({ albums: data }));
Live Example:
fetch('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => response.json())
.then(data => {
console.log(data);
});
Or we could call the parameter albums and use shorthand property notation:
fetch('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => response.json())
.then(albums => this.setState({ albums }));

Javascript Fetch and Map not working correctly

I'm trying to fetch a multiple page api and place the json within an array. I've set it up so it does the required number of fetches and is setting up the correct number of promises. I am getting 50+ different responses. However, when I try to map each of those responses, it only pulls the first set of data and pushes that repetitively to the array. What am I not doing correctly?
var data;
fetch(URL_ARTISTS3,{
method:'GET'
})
.then(response => response.json())
.then(json => {
data =json;
const apiPromises = [];
var pagesRequired = Math.ceil(json.setlists["#total"] / json.setlists["#itemsPerPage"]);
for (let i=pagesRequired; i>0;i--) {
var fetchurl = URL_ARTISTS3 + '?page = ' + i;
apiPromises.push(fetch(fetchurl, {
method: "GET",
body: json
}));
}
Promise.all(apiPromises)
.then(responses => {
var processedResponses = [];
responses.map(response => response.json()
.then(json => {
/****THIS LINE ADDS THE SAME JSON RESPONSE MULTIPLE TIMES*****/
processedResponses.push(json.setlists.setlist);
})
)
console.log('processedResponses: ', processedResponses)
});
I'm not sure it solves the problem, but one issue is that you are logging processedResponses before the promises are resolved.
You can simplify your code a lot by moving the response.json() call:
apiPromises.push(
fetch(fetchurl, {method: "GET", body: json})
.then(response => response.json())
.then(json => json.setlists.setlist);
);
// ...
Promise.all(apiPromises).then(processedResponses => console.log(processedResponses));

Categories