4

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>

13
  • 2
    Welcome to Stack Overflow! Please read through the help center, in particular How do I ask a good question? Your best bet here is to do your research, search for related topics on SO, and give it a go. If you get stuck and can't get unstuck after doing more research and searching, post a minimal reproducible example of your attempt and say specifically where you're stuck. People will be glad to help. Commented Apr 18, 2020 at 7:30
  • @palaѕн: I added my code Commented Apr 18, 2020 at 7:33
  • 1
    I am not getting this "3/20/20 should have a value of 4 (3 - 12)" how can 12 - 3 is 4? Commented Apr 18, 2020 at 7:40
  • data is not an array so you cannot map it. I made you a snippet so you have a minimal reproducible example Commented Apr 18, 2020 at 7:50
  • 1
    previous day was 3, on 3/20/20 it is 12, then how the "3/20/20 should have a value of 4"? Commented Apr 18, 2020 at 8:00

3 Answers 3

4

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)

Sign up to request clarification or add additional context in comments.

4 Comments

How can I can I get the initial number of cases ?
I don't understand the question. The initial number of cases is the first property in the case object.
In the newCases, I want to have this 3/19/20: 3 also. As, it is the day 1 since we started getting cases.
Interesting way to name a function :)
3

(async function() {
const {cases, deaths} = (await (await
fetch("https://corona.lmao.ninja/v2/historical/mauritius?lastdays=30")).json()).timeline;
console.log("Cases", diffEvents(cases));
console.log("Deaths", diffEvents(deaths));
})();

const diffEvents = (value) => {
const dates = Object.keys(value);

return dates.map((date, index) => {
  const currentDate = date;
  const prevDate = dates[index-1];
  return {
        date: currentDate,
        count: index>0 ? value[date] - value[dates[index-1]] : value[date]
       };
   });
 };
 

2 Comments

Does this do anything? And why a nested await?
The nested await is necessary because the json method is async.
2

$.getJSON('https://corona.lmao.ninja/v2/historical/mauritius?lastdays=30', function(data) {
    function fn(x, i) {
        return [this[i][0], this[i][1] - (i-1<0 ? 0 : this[i-1][1])];
     }
console.log(
       Object.fromEntries(
         Object.entries(data.timeline).map( ({0: type, 1: values}) =>
            [ type, Object.fromEntries(
                      (x=Object.entries(values)).map( fn.bind(x) )
                     )] ) )
);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.