我有一个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>
下面使用Array#reduce将服务器返回的绝对值转换为天数之间的差。
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句