Does someone know how to get specific data when working with JavaScript fetch?
I'm working with: https://apiv2.bitcoinaverage.com/constants/exchangerates/global
and not sure how to just pick 1 currency. I have a forEach loop that shows all, but unsure how to just pick one to show.
to show all I use:
${data.rates[rate].name}
${data.rates[rate].rate}<br>
When I try to just show one I tried with a few different, but I feel like this makes the most sense:
${data.rates[rate].name == dkk}
${data.rates[rate].rate}<br>
But it does nothing. Does someone know how to specify when you want to only show one set of data?
${data.rates[rate].name == dkk}
I'm assuming the ${} syntax here is javascript string interpolation. What you're saying here is "interpolate the value of the equality between .name and dkk". So this is probably displaying "true" or "false" for you, I'd assume.
What you want to do first is say
let displayName = '';
if (data.rates[rate].name === dkk) {
displayName = data.rates[rate].name;
}
And then interpolate ${displayName}.
If this isn't what you intend to do, we'd have to see more code.
let html = '';
for (let rateShort in data.rates) {
const rateObj = data.rates[rateShort];
html += `${rateObj.name} ${rateObj.rate}<br>`
}
Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in#Examples
fetch('https://apiv2.bitcoinaverage.com/constants/exchangerates/global')
.then(res => res.json())
.then(data => data.rates.AED)
.then(console.log)
since the fetch syntax returns a Promise, you can use .then to work with the data. in the code above I used .then to just return the AED(which is the rate of United Arab Emirates) object from the data recieved from the fetch. I hope it helps
OP here, figured it would be nice to comment how this was solved in case someone sees this in the future:
rates.forEach(currency=>{
if(data.rates[currency].name == 'Danish Krone'){ //if currency name == 'something'
output = output +
`
${data.rates[currency].name}
${data.rates[currency].rate}<br>
`
}
})
so basically you cant write ".name == dkk" to get the name of the currency. i actually had to write an if statement to check if the name == 'currency name'. also(for this api atleast) i couldt write the short version of the currency(dkk), i had to write the full name in the if statement. after that getting the name and rate of the currency was the same as when you loop through all.
hope this helps someone in the future if you end up here :)
Related
I'm quite new to coding. My goal is to make a simple "daily planner" page where you can save text in each line. I was trying to do this via local.storage, but I'm not quite sure what I'm doing wrong.
I've tried get vs setitem (which I'm not sure if there's a difference) I tried renaming my elements.
div.text(dailyPlanner[i].hour);
let textbox = $("<textarea>");
textbox.attr("data-hour", dailyPlanner[i].line);
textbox.addClass("col-8 col-md-10 description");
textbox.val(dailyPlanner[i].text);
if (currVal !== null) {
localStorage.setItem(textbox, line);
let textbox = localStorage.setItem(textbox)
}
The key needs to be a string so make the key "textbox" and also, what is the value of currVal? Can you confirm it isn't null?
I see two problems in your setIem call:
You are using an html node as a key (textbox) while you should use a string
You are using line as a value, which is undefined in your present code.
So you can try this instead, or adapt this to your case.
localStorage.setItem(dailyPlanner[i].text, dailyPlanner[i].line);
On my database i have a variable called user points, and i want to increase that variable by a value, lets say by 10, everytime i want.
I am doing this:
on firebase:
update({userPoints: +pointsToGet})
i am using the + to increase the value, but its not working. Is there any way that i can increase the userPoints without using the variable user points like this : userPoints = userPoints + pointsToGet
i tried using ++pointsToGet but it didnt work either
For Firestore
Yes you can by using firebase.firestore.FieldValue.increment(...).
update({ userPoints: firebase.firestore.FieldValue.increment(pointsToGet) })
For more information check out this tutorial: https://fireship.io/snippets/firestore-increment-tips/
Or for the official docs, here: https://firebase.google.com/docs/reference/js/firebase.firestore.FieldValue#static-increment
For Realtime Database
No there is no solution for that, I would recommend you to stick to the following:
update({ userPoints: oldUserPoints + pointsToGet })
Or check out this answer, where someone explains how to do this with a transaction (which is better for race conditions): https://stackoverflow.com/a/40405392/9150652
Offtopic
Also just for your information, +pointsToGet returns the numeric value of your variable (which probably already is a number, so it will just return that number).
It is not used to add 1 to a variable. You can transform a string to a number with it. I hope the following snippet explains it a little:
const createLog = (result) => { // Just a helper, so that we can see the "" for strings in the console
return JSON.stringify({result});
}
console.log(createLog( '123' ));
console.log(createLog( +'123' ));
console.log(createLog( '123' + '123' ));
console.log(createLog( +'123' + +'123' ));
Good evening.
I'm really struggling to get my head around this and I'm not sure if I'm missing something really stupid, but here is my code and my question.
const question = new Map();
question.set('question', 'What is the official name of the latest major JavaScript version?');
question.set(1, 'ES5');
question.set(2, 'ES6');
question.set(3, 'ES2015');
question.set(4, 'ES7');
question.set('correct', 3);
question.set(true, 'Correct answer :D');
question.set(false, 'Wrong, please try again!');
for (let [key, value] of question.entries()) {
if (typeof(key) === 'number') {
console.log(`Answer ${key}: ${value}`);
}
}
const ans = parseInt(prompt('Write the correct answer'));
console.log(question.get(ans === question.get('correct')));
Can someone please explain to me how, when I insert the right value into the prompt box; the interpreter?... knows to check the next line of code to display "Correct" or "Wrong in the console? depending on my input. I know we have a key of correct and its value is set to 3 but when do we tell it to execute the next lines of code depending on my answer? Does it just parse through the whole code, see a true statement and then executes whatever it is attached too, else execute the false statement? How, why? Apologies if I'm not coming through very clearly.
Your Map has an entry for key true and one for false. One of them is retrieved by using a key that corresponds to this expression:
ans === question.get('correct')
This expression returns true when the given answer is equal to the correct one, and false otherwise. This boolean result is then used as key for the next lookup in your set:
question.get(ans === question.get('correct'))
This effectively retrieves the value for either false or true -- as stored in your Map. And so the correct phrase is retrieved (and displayed).
If you would write that magic line a bit more verbose, it could look like this:
let output;
if (ans === question.get('correct')) { // get() returns 3 here.
output = question.get(true); // This retrieves 'Correct answer :D'
} else {
output = question.get(false); // This retrieves 'Wrong, please try again!'
}
console.log(output);
But realise how ans === question.get('correct') is a boolean expression, meaning it represents false or true, exactly what you want to pass as value to question.get in order to retrieve the phrase to be output.
So, instead of the if construct you can do:
let isCorrect = (ans === question.get('correct')); // false or true
let output = question.get(isCorrect); // This retrieves one of the two phrases
console.log(output);
And what those three lines do can be shortened into just one line:
console.log(question.get(ans === question.get('correct')));
NB: using Maps in this way doesn't look right. You should really use an array for the questions, and plain object(s) for the other stuff.
I am trying to compare the variable using javascipt:
response value: ""test#gmail.com""
response value i am getting it from server.
var str1="test#gmail.com"
var str2 =response;
if(str1===str2)
{
//
}
However not getting the proper result.
any idea on how to compare them ?
There are a few ways to achieve your goal:
1) You can remove all " from the response when doing your equality check:
if(str1===str2.replace(/['"]+/g, ''))
{
//
}
2) Change your server code to not include ". Doing so, would mean that your Javascript will not need to change.
3) Last option, add " to your str1:
var str1='"test#gmail.com"'
var str2 =response;
if(str1===str2)
{
//
}
Obviously I don't know enough about your requirements to tell you which one you should do, but my suggestion would be choice #2 because I think it's strange to return an email address wrapped in quotes, otherwise I would recommend #1.
You are trying to compare '""test#gmail.com""' with 'test#gmail.com'. They would never be equal.
Actually ""test#gmail.com"" is not a valid string. It might have been represented as '""test#gmail.com""' and "test#gmail.com" is a valid string (Same as 'test#gmail.com').
I have a JSON script which contain live matches. These changes every 5 minutes. The changes could for instance be the keys live_in or score. Beside this matches are also deleted and added to the JSON. I want to keep my html output updated at all time how can i do this the best possible way? So far i've set the updating speed to 5 seconds for testing purposes. I've tried so far to set the divs id to equal to the match_id and thereby update by
$('div#match-date-id-' + match['match_id']).html('test');
However does not seem to update. How can i do this the best possible way? i've created a plnkr which enable you to download it with a json snippet, which can be edited in order to check.
plnkr.co/edit/eQCShhW01OG5jU4VLx04?p=preview
My bad earlier on :-) Now I've done more thorough testing and updated the plunker code. What I found in the test: the filter was trying to use an undefined value (match.id), also the filter was trying to compare values from different datatypes (String vs. Integer); so it wasn't working as intended:
Original:
match = match.filter(
function(match) {
return match.id > lastId;
});
Corrected code:
match = match.filter(
function(match) {
return parseInt(match.match_id) > lastId;
});
Above match_id represents String datatype in your JSON file, so I had to convert it to Integer before comparison. More info about JSON data-types. Following the older filter functionality, no match passed the comparison test.
Also for testing purposes I commented out the following line:
if (match.match_id > lastLoadedMatch) {
//lastLoadedMatch = match.match_id
}
because in the second round of updates with the same testing data, no data passes that condition.
Also, I think you need to convert match_id to Integer as well; like following:
var matchId = parseInt(match.match_id)
if ( matchId > lastLoadedMatch) {
lastLoadedMatch = match.match_id
}
I hope you find it useful :-) + note I added a timestamp for those updates; so it's clearly visible that the updates take place now every 5 seconds.