Mapping Firebase element as array - javascript

I am developing a Pool betting app. Everything looks good and Im finishing the final module on it.
In firebase, I have a POOL of bets, that have many users. Any user has many matches with their betting on the matches. Like this:
When I do a request on the firebase like this:
fetchPoolData = async () => {
const { firebaseApp } = this.props;
await firebaseApp
.database()
.ref(`/pools/${this.props.location.state.pool.key}/users`)
.once("value")
.then(snapshot => {
this.setState({
poolData: this.snapshotToArray(snapshot),
isLoadingPool: false
});
});
};
Everything Looks great. Now I have an array of users, and want to make some calculations to get the points each user did on each match. So Im mapping the users like this:
this.props.poolData.map(user => {
allUserMatches.push(calculatePoints(user.matches, outcomeMatches));
});
The issue here is that user.matches IS NOT being retrieved as an array. Instead, its coming like a big json object that I can map and make my math to calculate the points.
How can I map this element? If I do a Object.keys I only got a object like this:
Object.keys(user.matches)
(66) ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "result", "topscorer"
And If I do a Object.entries, it is still not very usefull (because I need to do a find on the objects of the array, to get the elements filtered by an atribute of the object).
Object.entries(user.matches)
(66) [Array(2), Array(2), Array(2), Array(2)
Im lost here. What to do?

If you want to use such mapping you can go with
Object.keys(user.matches).map(key => user.matches[key])
Above will return you keys from each object which later on can be used in map of object through their keys.
Also it doesn't return as array as you have two wild properties (result and topscorer) that doesn't work like array indexes so it need to return them as Object instead of an Array
A way to retrieve all values without result and topscorer from that key value pair
Object.keys(user.matches).filter(key => Number.isInteger(parseInt(key))).map(key => user.matches[key]).

This will transform the object with number indices (type string) to the array you want:
Object.keys(user.matches).reduce((arr, key) => {
arr[parseInt(key)] = user.matches[key]
return arr
}, [])

Related

discord.js edit embed timeout

I made a fun command and I got no errors so far.
Here's the code:
const { MessageEmbed } = require('discord.js')
module.exports = {
name: "spin",
description: "spin",
permissions: ["SEND_MESSAGES"],
run: async (client, message, args) => {
if(message.author.bot) return;
let number = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36"];
let secondEmbed = new MessageEmbed()
.setTitle("The wheel is spinning...")
.setColor('#fc8eac')
.setTimestamp()
.addField("Spinner", `<#!${message.author.id}>`, true)
.addField("Result", ` <a:dotload:928216650614968321>`, true)
.setThumbnail('https://cdn.discordapp.com/emojis/928270805492699177.webp?size=160&quality=lossless')
.setFooter(`${message.author.tag}`, message.author.displayAvatarURL());
const m = await message.channel.send({embeds: [secondEmbed] })
let firstEmbed = new MessageEmbed()
.setTitle("The wheel has stopped spinning!")
.setColor('#fc8eac')
.setTimestamp()
.addField("Spinner", `<#!${message.author.id}>`, true)
.addField("Result", `${number[Math.floor(Math.random() * number.length)]}`, true)
.setThumbnail('https://cdn.discordapp.com/emojis/928270805492699177.webp?size=160&quality=lossless')
.setFooter(`${message.author.tag}`, message.author.displayAvatarURL());
await m.edit(({embeds: [firstEmbed] }), {timeout: 5000})
}
}
I'm having trouble on this line 'coz the embed gets edited in less than the given time length {timeout: 5000}
await m.edit(({embeds: [firstEmbed] }), {timeout: 5000})
I need help on how to fix this.
I'm not sure if there is a timeout option for the Message#edit method. At least I can't find it in the documentation.
However, you could use the good old setTimeout method to achieve the same:
setTimeout(() => {
m.edit({ embeds: [firstEmbed] })
}, 5000)

How to set a good date with chart js

I make a graph with NextJs and ChartJs on the stats of the covid (over the last 30 days) that I get with an API that provides me with the date and the stats :
timeline: {
cases: {
'5/13/21': 5902343,
'...' : ...
},
}
I managed to make the graph but I would like to place the date returned for each stats on the X line of my label
I managed to do this code (lineData is't my request) :
labels: [Object.keys(lineData.timeline.cases)],
but it shows me all the dates as one and the same object.
For now my label looks like this
labels: [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"29",
"30",
],
and I would like to replace values with the one provided by the api
Object.keys returns an array. So currently you have an array of array like:
labels: [ ['5/13/21'] ]
You can just do:
labels: Object.keys(lineData.timeline.cases) // labels: ['5/13/21']

Json array prints out as a string? Not array? [duplicate]

This question already has answers here:
How to compute the sum and average of elements in an array? [duplicate]
(35 answers)
Closed 1 year ago.
I'm currently getting my data from an API. It stores the weight log of animal checkups as shown below.
Currently I'm storing it in a html tag:
<h3 className='dogWeight'>Average: {item.weight}%</h3>
But it prints the numbers together as a string (i.e 100102103). Is there anyway I can add all numbers in the array to just show the Average?
{
"dog":[
{
"weight":[
"78",
"100",
"92",
"86",
"89",
"88",
"91",
"87"
],
"id":"1",
},
{
"weight":[
"75",
"89",
"95",
"93",
"99",
"82",
"89",
"76"
],
"id":"2",
},
You can loop over data.dog and reduce the weight values by accumulating the parsed integer weight values and dividing by the length of the weight array.
const data = {
"dog": [{
"id": "1",
"weight": [ "78", "100", "92", "86", "89", "88", "91", "87" ],
}, {
"id": "2",
"weight": [ "75", "89", "95", "93", "99", "82", "89", "76" ],
}]
};
const avg = vals => vals.reduce((sum, x) => sum + parseInt(x, 10), 0) / vals.length;
data.dog.forEach(({ id, weight }) =>
console.log(`ID: ${id}, Avg Weight: ${avg(weight).toFixed(2)}%`));
.as-console-wrapper { top: 0; max-heightL 100% !important; }

How are my popups not showing in my Leaflet map?

How can I make popups show up in leaflet that I plot using this code?
leaflet(df) %>%
addTiles() %>%
setView(-119.09, 43.70, zoom = 5) %>%
addCircles(~long, ~lat, popup=df$hrus, color="#ffa500") %>%
addLegend("bottomright", colors= "#ffa500", labels="HRUs", title="P")
I can see the dots, but nothing shows up on the popup (Inside RStudio view pane). I tried saving it as HTML, but the saved page neither has the basemap nor the popup
How can I do it?
dput(df)
structure(list(lat = structure(c(41.26124, 41.45247, 41.50923,
41.57602, 41.62999, 41.60664, 41.63508, 41.83411, 41.84721, 41.84382,
41.83294, 41.85096, 41.60179, 41.8572, 41.64224, 41.85058, 41.14342,
41.77109, 41.35783, 41.39253, 41.78496, 41.5982, 41.66492, 41.70302,
41.56481, 41.55544, 41.59929, 41.71257, 41.85876, 41.42739, 41.39722,
41.76483, 41.49387, 41.46879, 41.50355, 41.95393, 41.8932, 41.96956,
41.76675, 41.93061, 41.93767, 41.53439, 41.51667, 41.50472, 41.5053,
41.67506, 41.68689, 41.78533, 41.79546, 41.87722), .Dim = 50L),
long = structure(c(-116.21489, -114.91972, -114.74541, -114.72553,
-114.83965, -114.81267, -114.84702, -113.49586, -113.48851,
-113.46151, -113.45017, -113.38449, -114.91356, -113.41496,
-114.85369, -113.50472, -116.21671, -114.25468, -116.32436,
-116.18391, -114.23875, -115.05154, -114.95098, -114.99438,
-115.75044, -115.89944, -115.84581, -114.9099, -114.19781,
-116.59131, -116.53819, -114.07782, -116.38066, -116.4347,
-116.33524, -113.51231, -113.51787, -113.55034, -114.96587,
-113.34303, -113.24616, -116.28699, -116.60549, -116.63497,
-116.55531, -115.19046, -114.72527, -114.64668, -114.54489,
-113.59969), .Dim = 50L), hrus = structure(1:50, .Label = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
"13", "14", "15", "16", "17", "18", "19", "20", "21", "22",
"23", "24", "25", "26", "27", "28", "29", "30", "31", "32",
"33", "34", "35", "36", "37", "38", "39", "40", "41", "42",
"43", "44", "45", "46", "47", "48", "49", "50"), class = "factor")), .Names = c("lat",
"long", "hrus"), row.names = c(NA, 50L), class = "data.frame")

How to make a new array of strings derived from an old array, using a delimeter

I have an array of strings and I want to make a new one joining the strings of the arrays until the delimeter character is shown.For example I have this array of strings:
["5", "2", "0", "1", "6", "2", "7", "0", "1", "9", "9", "0", "0", "", "5", "2", "0", "3", "4", "1", "1", "0", "2", "1", "9", "8", "4", ""]
and I want to make a new one like this:
["5201627019900","5203411021984"]
The delimeter of those items in the array is the "" between them.Any help?
var result = array.join("").trim().split(/\s/ /*or " " */);
var result = array.reduce((a,b) => { return a+b; }).trim().split(" ");

Categories

Resources