我有一个 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)
关于javascript - 在 JavaScript 中解析 JSON 对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61285637/