在 JavaScript 中解析 JSON 对象数组
问题我有一个 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).forEach(function(d) {
acc = (acc || 0) - e;
});
});
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 > 0)
}
function deltas(arr) {
let prev = 0
return arr.reduce((acc, ) => {
acc.push()
prev = curr
return acc
}, [])
}
go()
页:
[1]