使用Nuxt异步数据,我正在以以下格式获取带有嵌套数组的JSON对象:
"topic_list": {
"topics": [
{
"id": 9148,
"title": "A",
"views": 12
},
{
"id": 3228,
"title": "B",
"views": 88
}
]
}
数据正在异步加载:
export default {
data () {
return { topics: 'default', users: '0', views: '0', total: [] }
},
asyncData ({ params }, callback) {
axios.get(`data.json`)
.then((res) => {
callback(null, { topics: res.data.topic_list.topics, users: res.data.users,
})
})
}
}
我想知道什么是计算所有视图总数的最佳方法。我知道reduce()并想象这些值需要放入数组中-但是如何异步加载数据呢?
答案 0 :(得分:1)
只需汇总视图
callback(null, { topics: res.data.topic_list.topics, users: res.data.users, totalOfViews:
res.data.topic_list.topics.reduce((sum, currentItem) => (currentItem.views + sum), 0) })
这将添加视图:
res.data.topic_list.topics.reduce((sum, currentItem) => (currentItem.views + sum), 0)