quite new to working with both api's and javascript. I'm trying to console.log out the amount of times a friend of mine has died in rust, but all items are named "name:" An img of what I mean:
I'm using axios to call the api, here's the code:
var statsApi = 'http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?';
var statsAppId = 'appid='+252490+'&'
var statsSteamApiKey = 'key='+process.env.STEAM_API+'&';
var statsUserArg = 'steamid='+userID;
var steamStatsApi = statsApi + statsAppId + statsSteamApiKey + statsUserArg;
axios
.get(steamStatsApi)
.then((res) =>{
message.channel.send("AAAA");
// console.log(res['data']['playerstats']['stats']['name' == 'deaths']);
for(re in res['data']['playerstats']['stats']) {
if(re['name'] === 'deaths') {
console.log('test');
console.log(re['value']);
}
else {
console.log('Fel');
}
}
})
.catch((err) => {
console.error('Error:', err);
})
Again if anyone knows how to get the amount of 'deaths' I'd be super grateful.
Turns out it was quite easy, if anyone has this problem just use the following code which I am about to provide:
var index = -1;
for(var i = 0; i < Object.keys(res['data']['playerstats']['stats']).length; i++) {
if(res['data']['playerstats']['stats'][i]['name'] === 'deaths') {
index = i;
var userDeaths = res['data']['playerstats']['stats'][index]['value'];
break;
}
}
What this does is that it loops trough every object named "name:" until it finds 'deaths' in one of them. I change i to that and now i'm able to print out the value which i'm looking for.
Please check this code:
let res = [{ name: "deaths", value: 2694}, {name:"bullet_fired", value: 343328}];
let i = 0;
for(i=0;i<res.length;i++){
if(res[i].name =="deaths"){
console.log(res[i].value);
}
}
Here res variable will contain your json values.
Related
I'm trying to fetch API data and insert it in a table ( I am using VS code and live server). So far I've got the right data from the ApI and my thought is to loop that data and send it. When I try to loop the data I only get the last football match sent - Why don't I get all 13 games? I need some advice or suggestions on how to succeed.
export function getMatchData() {
return fetch('https://stryk.herokuapp.com/strycket2022')
.then(function (response) {
return response.json();
})
.then(function (data) {
let gameArray = data.playedGames;
let gameInfo = "";
for (let i = 0; i < gameArray.length; i++) {
gameInfo = data.playedGames[i].teams[1].name + " VS " + data.playedGames[i].teams[2].name;
}
console.log(gameInfo);
return gameInfo;
});
As already mentioned,
You are setting a new value in the gameInfo variable every time, so you only see the last value
Try creating an array and pushing the value there
Here's an example:
fetch('https://stryk.herokuapp.com/strycket2022')
.then(response => response.json())
.then(function (data) {
const gameArray = data.playedGames;
let gameInfo = [];
gameArray.ForEach((game) => {
const newGame = game.teams[1].name + " VS " + game.teams[2].name;
gameInfo.push(newGame);
});
console.log(gameInfo);
return gameInfo;
});
create empty array or object instead string. i'm about variable gameInfo. and on each interation you have to add new value (gameInfo.push(value) if it will be array, for example). so you will get array that contains information about each item. you will able to use it for your goals
in your vaiant you rewriting value in gameInfo on every interation and at the end of loop you are getting only last value
Maybe this will help to get you on the right track?
fetch('https://stryk.herokuapp.com/strycket2022')
.then(response=>response.json())
.then(function (data) {
let gameArray = data.playedGames;
let gameInfo = [];
for (let i = 0; i < gameArray.length; i++) {
gameInfo.push( data.playedGames[i].teams[1].name + " VS " + data.playedGames[i].teams[2].name);
}
console.log(gameInfo.join("\n"));
});
Or, even shorter:
fetch('https://stryk.herokuapp.com/strycket2022')
.then(r=>r.json())
.then(dat=>console.log(dat.playedGames.map(g=>g.teams[1].name+" vs "+g.teams[2].name).join("\n")));
const res = await fetch('https://stryk.herokuapp.com/strycket2022')
const data = await res.json();
let gameArray = data.playedGames;
let gameInfo = [];
gameArray.map(game => {
gameInfo.push( game.teams[1].name + " VS " + game.teams[2].name);
})
console.log(gameInfo);
I've been working on a project and I'm currently working on a function which dynamically creates a dictionary data structure. The key used is the roll number of the student, and the value is the student's name.
But I'm unable to iterate through this dictionary. I've tried displaying the dictionary on console, but all I could see is an empty dictionary. I could see the elements in it, only if I expand it further. And when I display length using Obj.length on console, it displays 'undefined'. I've read on other questions that Obj.length only works on arrays(i.e., enumerable types), and I've tried using an array instead of a dictionary. In that case, it shows an empty array and would not show values unless I manually expand it. I've also tried Obj.keys() method on the dictionary, and I've encountered the same issue.
This is the function's code:
function dictGenerator(rollnos, selectedValue) {
var dict = {};
for(let i = 0; i < rollnos.length; i++) {
get(child(dbref, "RegisterNos/" + rollnos[i])).then((snapshot)=>{
if(Object.keys(snapshot.val()).length-1 == selectedValue){
dict[rollnos[i]] = snapshot.val()["name"];
}
});
}
console.log(dict);
console.log(dict.length);
}
}
Any help on how I could iterate through my dictionary would be appreciated, Thank you.
Edit:
code implementation using promises.
function dictGenerator(regnos, selectedValue) {
const get_dict = async () => {
var dict = {};
for(let i = 0; i < regnos.length; i++){
get(child(dbref, "RegisterNos/" + regnos[i])).then((snapshot)=>{
if(Object.keys(snapshot.val()).length-1 == selectedValue){
dict[regnos[i]] = snapshot.val()["name"];
}
});
}
return dict;
};
get_dict().then((dict) => {
console.log(dict);
});
}
Basing on comments made by VALZ and JaredSmith, this is the working code:
function dictGenerator(regnos, selectedValue) {
const get_dict = async () => {
var dict = {};
for(let i = 0; i < regnos.length; i++){
await get(child(dbref, "RegisterNos/" + regnos[i])).then((snapshot)=>{
if(Object.keys(snapshot.val()).length-1 == selectedValue){
dict[regnos[i]] = snapshot.val()["name"];
}
});
}
return dict;
};
get_dict().then((dict) => {
console.log(dict);
});
}
}
I try to get data from the array but I get undefined
please check the image of my problem
I don't know what I'm missing
please help
I have an array called nameTable of string
when I console.log(this.nameTable) I got this : check the image please
enter image description here
and when I click to arrow I got this : check image please
enter image description here
the problem is the table has 5 element I want to show them so I make for loop to do that
for (let i = 0; i < 5; i++){
console.log(this.nameTable[i])
}
but us you can see in the image I got undefined
enter image description here
here the code :
employeeL:Array<Awinjard> = [];
inv_agentTab: Array<Inv_agent> = [];
drafbiesTab: Array<Drafbies> = [];
nameemployee: string = "";
inv_agentNombre: number = 0;
matriculeTable: Array<number> = [];
nameTable:Array<string> = [];
validatationTable: Array<number> = [];
ngOnInit() {
this.folder = this.activatedRoute.snapshot.paramMap.get('id');
this.awinjard.getAwinjardMatricule().subscribe(res => {
this.inv_agentTab = res as Array<Inv_agent>
this.inv_agentTab.forEach(element => {
this.matriculeTable[this.inv_agentNombre] = element.AGENT;
this.validatationTable[this.inv_agentNombre] = element.VLD;
this.inv_agentNombre++;
this.awinjard.getAwinjardNameAr().subscribe(res2 => {
this.drafbiesTab = res2 as Array<Drafbies>
this.drafbiesTab=this.drafbiesTab.filter((employee)=>employee.DECAFFE==element.AGENT)
this.nameemployee = this.drafbiesTab[0].AR_DELAFFE;
this.nameTable.push(this.nameemployee);
})
});
for (let i = 0; i < 5; i++){
// here the problem I can't get the data form nameTable array
console.log(this.nameTable[i])
let awin= <Awinjard> {
matricule: this.matriculeTable[i],
fullname: this.nameTable[i],
status: true,
done: 1,
mustBeDone:40
}
this.employeeL.push(awin);
}
})
}
You have subscribed to getAwinjardNameAr and before that response, you are trying to access the nameTable array, which is why you get undefined. #raishav-hanspal's solution is right to solve your issue, but a code change can keep things straightforward. I suggest you to write that code inside your for loop inside your subscribe. Here's the alteration:
this.awinjard.getAwinjardNameAr().subscribe(res2 => {
this.drafbiesTab = res2 as Array<Drafbies>
this.drafbiesTab=this.drafbiesTab.filter((employee)=>employee.DECAFFE==element.AGENT)
this.nameemployee = this.drafbiesTab[0].AR_DELAFFE;
this.nameTable.push(this.nameemployee);
let awin= <Awinjard> {
matricule: this.matriculeTable[this.inv_agentNombre],
fullname: this.nameemployee,
status: true,
done: 1,
mustBeDone:40
}
this.employeeL.push(awin);
})
You can move the code where you're logging nameTable[] inside the subscribe (where you are pushing the values into nameTable[]).
A complete solution is to use complete in subscribe() -->
this.awinjard.getAwinjardNameAr().subscribe(res2 => {
this.drafbiesTab = res2 as Array<Drafbies>
this.drafbiesTab=this.drafbiesTab.filter((employee)=>employee.DECAFFE==element.AGENT)
this.nameemployee = this.drafbiesTab[0].AR_DELAFFE;
this.nameTable.push(this.nameemployee);
},err => {console.log(err)}, ()=> {
for (let i = 0; i < 5; i++){
// here the problem I can't get the data form nameTable array
console.log(this.nameTable[i])}})
});
You can read more on https://angular.io/guide/observables
I have an api calling data from db, one of column has Image file name stored. I want to split the file and get the last 3 letters of each filename after the DOT. I am stuck here:
axios.get('/api/v1/chats/messages/' + this.chat).then(response => {
this.result = response.data;
this.details = this.result.data;
for (var j = 0; j < this.details.length; j++) {
this.str = this.details[j].image;
this.details[j].image_type = this.str.split(".");
}
console.log(this.details)
})
.catch(error => {
toastr.error('Something went wrong', 'Error', {
positionClass: 'toast-bottom-right'
});
this.cancelAutoUpdate();
});
Would really appreciate if someone could help me OR please let me know if theres any other way to get the file extension in vue js. Thanks :)
function split splits a string into an array by a separator. You got an array, but forgot to get the array element you are interested in.
You need to replace this.str.split("."); to this.str.split(".")[1]
const details = [
{
image: 'image1.jpg',
},
{
image: 'image2.png',
},
{
image: 'image3.gif',
}
]
for (let detail of details) {
let str = detail.image;
detail.image_type = str.split(".")[1];
}
console.log(details)
I'm just starting to figure out React by putting together a bit of code from different parts, and from an online course.
I'm using React, Next and Axios to get an API from a cryptocurrency server.
The main issue I'm facing is:
I am able to console.log(coinObjects) under getInitialProps, and it displays the object correctly
Despite this, coinObjects does not get rendered in {this.props.coinObjects}
As a possible clue, linksArr does get rendered in {this.props.linksArr}
The code I have is as follows:
class MainIndex extends Component {
static async getInitialProps(props) {
// setup - empty array and list of coins
const coinList = ["NEO", "ETH", "BTC"];
const numCoins = coinList.length;
const coinObjects = [];
const linksArr = [];
const isServer = typeof window === "undefined";
// API GET
const baseUrl = "https://min-api.cryptocompare.com/data/histohour?";
for (let coinName of coinList) {
linksArr.push(
baseUrl.concat("fsym=", coinName, "&tsym=", "USD", "&limit=", "3")
);
}
const getObj = async linksArr => {
try {
let res = await axios.all(linksArr.map(l => axios.get(l)));
for (let i = 0; i < linksArr.length; i++) {
coinObjects[coinList[i]] = res[i].data.Data;
}
} catch (err) {
console.error(err);
}
};
await getObj(linksArr);
console.log(coinObjects);
// Return updated arrays
if (isServer) {
return { coinObjects, numCoins, linksArr };
} else {
return {};
}
}
render() {
return (
<Layout>
<h2>
CoinObject has {this.props.coinObjects.length} coins
// Returns 0
<br />
LinksArr has {this.props.linksArr.length} links
// Returns 3
</h2>
</Layout>
);
}
}
Could anyone please help me? I've exhausted all the Google searches, Stackoverflow posts and coding friends that I can find (just 1). I can't figure out what's wrong, and I hope that this isn't a silly question because I've been tweaking and changing things extensively, but have yet to figure out what's wrong.
Here the coinObject is set to an array:
const coinObjects = [];
But later is treated as an Object:
coinObjects[coinList[i]] = res[i].data.Data;
That means that you would want to add to the array like this:
for (let i = 0; i < linksArr.length; i++) {
let data = res[i].data.Data;
let name = coinList[i];
coinObjects.push({ name: name, data: data });
}