get data from json file using javascript and show data out table - javascript

I tried to get the data from the json file with javascript but it doesn't output the data
here is my code:
fetch('https://raw.githubusercontent.com/trvodi/test/main/json1.json')
.then((res) => res.json())
.then((data) => {
var json = data;
var i;
var iLength = json.data.item.length;
for (i = 0; i < iLength; i++) {
alert(json.data.item[i].FromMember);
}
}).catch((err) => {
console.log(err)
})
please help me. thank you

If you'd add the following line:
console.log(json.data.item, json.data.item.length);
You'll see that json.data.item.length is undefined because json.data.item is an object.
I'd recommend using
for (let i in json.data.item) {
let item = json.data.item[i];
console.log(item.FromMember);
}
To loop over the objects as shown in this demo:
fetch('https://raw.githubusercontent.com/trvodi/test/main/json1.json')
.then((res) => res.json())
.then((data) => {
for (let i in data.data.item) {
let item = data.data.item[i];
console.log(item.FromMember);
}
})
.catch((err) => {
console.log(err)
})
For more info about why (and alternatives) I'd choose for (let i in json.data.item), please see the following question/answer:
How to loop through a plain JavaScript object with the objects as members?

Related

Elements only appear after I input something

For some reason, everything is being initialized properly when I load the page for the first time, except for the paymentID and Amount, which are being display only after I click on something or input anything in a text box.
This is my code which initializes my webpage.
created: function () {
// Initializing persons
AXIOS.get('/persons')
.then(response => {
this.persons = response.data;
this.persons.forEach(person => this.getRegistrations(person.name))
this.persons.forEach(person =>
person.eventsAttended.forEach(event => {
this.getPaymentofRegistrations(person.name, event.name)
}))
})
.catch(e => {this.errorPerson = e});
.
.
.
.
getRegistrations: function (personName) {
AXIOS.get('/events/person/'.concat(personName))
.then(response => {
if (!response.data || response.data.length <= 0) return;
let indexPart = this.persons.map(x => x.name).indexOf(personName);
this.persons[indexPart].eventsAttended = [];
response.data.forEach(event => {
this.persons[indexPart].eventsAttended.push(event);
});
})
.catch(e => {
e = e.response.data.message ? e.response.data.message : e;
console.log(e);
});
},
getPaymentofRegistrations: function (personName, eventName) {
AXIOS.get('/registrations?person='+personName+'&event='+eventName)
.then(response => {
if (!response.data || response.data.length <= 0) return;
let indexPart1 = this.persons.map(x => x.name).indexOf(personName);
let indexPart2 = this.persons[indexPart1].eventsAttended.map(x => x.name).indexOf(eventName);
this.persons[indexPart1].eventsAttended[indexPart2].paymentId = response.data.bitcoin.userID;
this.persons[indexPart1].eventsAttended[indexPart2].paymentAmount = response.data.bitcoin.amount;
})
.catch(e => {
console.log(e)
})
}
Images attached for a better understanding of the problem.
It only takes writing a letter in a text box (without even clicking on a reactive button) for the Payment and Amount info to appear:
This code is very complex and hard to understand but if I should make a bid Vue.set can help for you:
https://v2.vuejs.org/v2/guide/reactivity.html#For-Objects
or you can store eventsAttended collections in another data property, not as a nested object.

Unable to save fetched data in Jquery

I'm working on my front-end, and I've arrived at a roadblock. I'm trying to fetch data from my back-end, and it is actually fetching the data. But only after everything else? I'll show you.
$(function(){
function GetURLId() {
var url = window.location.href;
var path = url.substring(url.lastIndexOf('/') + 1);
var id = path.substring(path.lastIndexOf('?id=') + 4, path.lastIndexOf("?id") + 5)
return id;
}
var url = 'https://localhost:5001/api/rental/byId/' + GetURLId();
fetch(url)
.then((resp) => resp.json())
.then(function(data) {
Object.keys(data).forEach(key => {
console.log(`${key}: ${data[key]}`);
})
});
});
So first I get which id I'm working with out of the URL. Then where the problem lays is the code under it. I'm able to fetch my data as it console.logs this:
id: 2
status: "Open"
damage: true
So the data does actually fetch from my back-end. But now, everytime I try to save the data it goes undefined. I've tried:
$(function(){
var rental = []; // Added an array
var url = 'https://localhost:5001/api/rental/byId/' + GetURLId();
fetch(url)
.then((resp) => resp.json())
.then(function(data) {
Object.keys(data).forEach(key => {
console.log(`${key}: ${data[key]}`);
rental.push(rental[key] = data[key]);
})
});
console.log(rental['id']); // Returns undefined
});
And:
var rental = []; // Added an array outside of the function
$(function(){
var url = 'https://localhost:5001/api/rental/byId/' + GetURLId();
fetch(url)
.then((resp) => resp.json())
.then(function(data) {
Object.keys(data).forEach(key => {
console.log(`${key}: ${data[key]}`);
rental.push(rental[key] = data[key]);
})
});
console.log(rental['id']); // Returns undefined
});
But! With the last one where the rental is outside of the function, I can actually call it in the console. And in the console it actually does return the value.
Inside Console:
> rental["id"]
< 2
Lastly I've tried to check the value of the key and value inside of the fetch, like this:
$(function(){
var url = 'https://localhost:5001/api/rental/byId/' + GetURLId();
fetch(url)
.then((resp) => resp.json())
.then(function(data) {
Object.keys(data).forEach(key => {
if(key == "status" && data[key] != "Reserved") {
console.log(`${key}: ${data[key]}`); // Returns damage: undefined 3 times
}
})
});
});
But this as well doesn't work. It returns damage: undefined 3 times in console.
So if anyone knows what is going on here it would be awesome!
Thanks alot in advance.
Fetch requests are asynchronous. This means that when you call fetch it might take a while to complete it, so JavaScript allows the rest of the code to continue without blocking. So logging anything to the console before your request has finished will obviously result in an empty array.
Also, Arrays are index-, not name based in JavaScript. However, because arrays are essentially objects it still works, but you should never do the following below.
var rental = [];
rental['id'] = 'foo';
console.log(rental['id']);
Instead use a plain object which is meant to be used that way.
var rental = {};
rental['id'] = 'foo';
console.log(rental['id']);
In your last example you seem to do everything just fine. Are you sure your fetched data does not have a value of undefined in its structure? It would help to see what the data looks like.
The answer: 2 errors in my code.
- First I didn't properly account for the asynchronous nature of the code.
- Second, when trying to fix it with another then block and executing my code in there. I didn't return a value in the proceeding then block, but the forEach instead.
fetch(url)
.then(resp => resp.json())
.then(data => {
var rentalStatus;
Object.keys(data).forEach(key => {
rental[key] = data[key];
if(key == "status") {
rentalStatus = data[key];
}
})
return rentalStatus;
})
.then(rentalStatus => {
console.log(rental["id"]); // This does return the id now!
if(rentalStatus == "Reserved") {
$("#assign-items").removeClass("d-none");
}
}).catch(error => {
console.log("Error:" + error);
});

Axios Get request to show in browser

axios.get("https://swapi.co/api/people")
.then(response => {
for(let i = 0; i < response.data.length; i++){
const h1 = document.createElement('h1')
h1.textContent = response.data[i].name
document.body.appendChild(h1)
}
})
.catch(error => console.log(error))
I am trying to get this api link to create a list in browser, showing the names. I have gotten this to work with a free api from VSchool that I was able to create myself with Post request. But now that I have Swapi in there to show Star Wars characters, nothing will show. My logic for it all hasn't changed though. Am I missing something? Thank you
You are using improper response format. Add response.results instead of response.data -
axios.get("https://swapi.co/api/people")
.then(response => {
for(let i = 0; i < response.results.length; i++){
const h1 = document.createElement('h1')
h1.textContent = response.results[i].name
document.body.appendChild(h1)
}
})
.catch(error => console.log(error))

How to display nested data on the DOM?

Trying to fetch data from an API and add it to the DOM
Specifically, an array that contains objects.
Below is an example of what the API returns in the console.
I’m using a for loop and a for…in loop to access the array within the object
Code below
const getNews = document.getElementById('btn')
heyThere = () => {
axios.get('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=APIKEY')
.then(function (response) {
for (let i = 0; i <= response.data.articles.length; i++) {
for (key in response.data.articles[i]) {
ham.innerHTML = (response.data.articles)
}
}
console.log(response)
console.log(typeof response)
})
.catch(function (error) {
console.log(error);
})
}
getNews.addEventListener('click', heyThere)
The above code prints the following to the DOM
What’s the correct way to access the full list of articles(20 articles) and print them to the DOM?
You need to access the specific properties of response.data.articles[i] that you want to display, and create the desired HTML for each of them. Something like:
const getNews = document.getElementById('btn')
heyThere = () => {
axios.get('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=APIKEY')
.then(function(response) {
let html = '';
response.data.articles.each(article => {
html += '<div class="article">';
html += `<div class="author">${article.author}</div>`;
html += `<div class="description">${article.description}</div>`;
html += '</div>';
});
ham.innerHTML = html;
console.log(response)
console.log(typeof response)
})
.catch(function(error) {
console.log(error);
})
}
getNews.addEventListener('click', heyThere)
The solution below prints the articles to the DOM as a list.
heyThere = () => {
axios.get('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=APIKEY')
.then(function (response) {
let news = response.data.articles
for (let i = 0, len = news.length; i < len; i++) {
console.log(news[i])
let li = document.createElement('li')
li.innerHTML = JSON.stringify(news[i].title)
document.querySelector('#ham').appendChild(li)
}
})
.catch(function (error) {
console.log(error);
})
}
getNews.addEventListener('click', heyThere)
Below are the articles printed to the page
Altering the response with dot notation allows one to return a list of URLs, authors, etc. For example, li.innerHTML = JSON.stringify(news[i].url)
Hope this is helpful!

React Axios API call with array loop giving wrong order?

I was learning react and doing some axios api call with an array. I did a code on gathering data through coinmarketcap api to learn.
So, my intention was to get the prices from the api with a hardcoded array of cryptocurrency ids and push them into an array of prices. But I ran into a problem with the prices array, as the prices were all jumbled up. I was supposed to get an array in this order
[bitcoinprice, ethereumprice, stellarprice, rippleprice]
but when I ran it in the browser, the prices came randomly and not in this order, sometimes I got my order, sometimes it didn't. I used a button which onClick called the getPrice method. Does anyone know what went wrong with my code? Thanks!
constructor(){
super();
this.state = {
cryptos:["bitcoin","ethereum","stellar","ripple"],
prices:[]
};
this.getPrice = this.getPrice.bind(this);
}
getPrice(){
const cryptos = this.state.cryptos;
console.log(cryptos);
for (var i = 0; i < cryptos.length; i++){
const cryptoUrl = 'https://api.coinmarketcap.com/v1/ticker/' + cryptos[i];
axios.get(cryptoUrl)
.then((response) => {
const data = response.data[0];
console.log(data.price_usd);
this.state.prices.push(data.price_usd);
console.log(this.state.prices);
})
.catch((error) => {
console.log(error);
});
}
}
If you want to receive the data in the order of the asynchronous calls you make, you can use Promise.all, that waits until all the promises of an array get executed and are resolved, returning the values in the order they were executed.
const cryptos = ['bitcoin', 'ethereum', 'stellar', 'ripple'];
const arr = [];
for (var i = 0; i < cryptos.length; i++){
const cryptoUrl = 'https://api.coinmarketcap.com/v1/ticker/' + cryptos[i];
arr.push(axios.get(cryptoUrl));
}
Promise.all(arr).then((response) =>
response.map(res => console.log(res.data[0].name, res.data[0].price_usd))
).catch((err) => console.log(err));
You could use a closure in the for loop to capture the value of i and use it as the index once the data is returned rather than using push:
getPrice(){
const cryptos = this.state.cryptos;
console.log(cryptos);
for (var i = 0; i < cryptos.length; i++) {
const cryptoUrl = 'https://api.coinmarketcap.com/v1/ticker/' + cryptos[i];
(function (x) {
axios.get(cryptoUrl)
.then((response) => {
const data = response.data[0];
console.log(data.price_usd);
var newPrices = this.state.prices;
newPrices[x] = data.price_usd;
this.setState({prices: newPrices});
console.log(this.state.prices);
})
.catch((error) => {
console.log(error);
});
})(i);
}
}

Categories