问题
我有一个 JSON 字符串:
- {
- "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
- }
- }
- }
复制代码
我试图实现的是解决案例、死亡并将值恢复到 JavaScript 中的单独数组中。
比如病例数,我想求病例数和上一个日期的差,起始日期为 3/19/20,初始病例数为 3。我想应用相同的逻辑到死亡和康复。所以 3/20/20 的值应该是 9 (12-3)
最后,我想将这些数据存储在一个数组中,以便在图表上使用它。有人可以帮我用 JavaScript 或 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>
复制代码
回答
下面使用reduce将服务器返回的对象转换为天差。
- const entries = Object.entries
- const fromEntries = Object.fromEntries
- const log = console.log
- const URL = "https://corona.lmao.ninja/v2/historical/mauritius?lastdays=30"
- async function go() {
- const { timeline: { cases, deaths } } = await (await fetch(URL)).json()
- const newCases = fromEntries(nonZero(deltas(entries(cases))))
- const newDeaths = fromEntries(nonZero(deltas(entries(deaths))))
- log(`New cases: ${JSON.stringify(newCases, null, 2)}`)
- log(`New deaths: ${JSON.stringify(newDeaths, null, 2)}`)
- }
- function nonZero(arr) {
- return arr.filter(([_,v]) => v > 0)
- }
- function deltas(arr) {
- let prev = 0
- return arr.reduce((acc, [date, curr]) => {
- acc.push([date, curr - prev])
- prev = curr
- return acc
- }, [])
- }
- go()
复制代码
|