I have a JSON string:
{
"country": "Mauritius",
"provinces": [
"mainland"
],
"timeline": {
"cases": {
"3/19/20": 3,
"3/20/20": 12,
"3/21/20": 14,
"3/22/20": 28,
[...]
"4/17/20": 324
},
"deaths": {
"3/19/20": 0,
"3/20/20": 0,
"3/21/20": 1,
"3/22/20": 2,
[...]
"4/17/20": 9
},
"recovered": {
"3/19/20": 0,
"3/20/20": 0,
"3/21/20": 0,
"3/22/20": 0,
[...]
"4/17/20": 108
}
}
}
What I want to achieve is to parse the value of cases, deaths and recovered into separate arrays in JavaScript.
For example, the number of cases, I want to find the difference in the number of cases from the previous date, with starting date as 3/19/20
within an initial cases of 3. I want to apply same logic for deaths and recovered. Hence, 3/20/20 should have a value of 9 (12 - 3)
Finally, I want to store each of this in arrays to use this data on a chart. Can someone please help me to parse this data in JavaScript or JQuery?
$.getJSON('https://corona.lmao.ninja/v2/historical/mauritius?lastdays=30', function(data) {
let result = data.map(function(e) {
return {
cases: e.timeline.cases,
deaths: e.timeline.deaths,
recovered: e.timeline.recovered
};
}).reduce(function(acc, e) {
Object.keys(e).forEach(function(t) {
Object.keys(e[t]).forEach(function(d) {
acc[t][d] = (acc[t][d] || 0) - e[t][d];
});
});
return acc;
}, {
deaths: {},
recovered: {},
cases: {}
});
console.log(result)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
The following uses Array#reduce to transform the absolute values returned from the server, into the differences between days.
const entries = Object.entries, log = console.log, toJSON = JSON.stringify
const Δ = (arr, prev = 0) =>
arr.reduce((acc, [date, curr]) =>
(acc[date] = curr - prev, prev = curr, acc), {})
const AUTHORITY = 'corona.lmao.ninja'
async function fetchDeltas({ country, days = 30 }) {
const url = `//${AUTHORITY}/v2/historical/${country}?lastdays=${days}`
const { timeline: { cases, deaths, recovered } } = await (await fetch(url)).json()
return {
newCases: Δ(entries(cases)),
newDeaths: Δ(entries(deaths)),
newRecoveries: Δ(entries(recovered))
}
}
fetchDeltas({ country: 'mauritius' }).then(log)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With