我有一个类似下面的JSON,需要通过从JSON中的链接获取历史记录和个人详细信息来创建具有用户完整配置文件的数据结构。有什么想法我怎么用axios做它?
JSON={
0:{
userid:"...",
details:"http:://<user>/profile",
history:"http://<user>/history"
}
1:{
userid:"...",
details:"http:://<user>/profile",
history:"http://<user>/history"
}
2:{
userid:"...",
details:"http:://<user>/profile",
history:"http://<user>/history"
}
}
期望的结果json是
JSON:{
0:{
userid:"1",
name:"<datafrom profile>",
age:"<data from profile>",
last_login:"<data from history>"
},
1:{
userid:"1",
name:"<datafrom profile>",
age:"<data from profile>",
last_login:"<data from history>"
},
2:{
userid:"2",
name:"<datafrom profile>",
age:"<data from profile>",
last_login:"<data from history>"
},
}
答案 0 :(得分:1)
假设细节和历史键值对是合法的URL。我将在此示例中使用http://someDataUrl.com
和http://someHistoryUrl.com
。
另外,不确定你的终端会返回什么,所以我做了一些例子。
function getDataInfo(user){
return axios.get(`http://someDataUrl.com/${user}`)
}
function getHistoryInfo(user){
return axios.get(`http://someHistoryUrl.com/${user}`)
}
let json = {}
axios.all([getDataInfo(), getHistoryInfo()])
.then(axios.spread(function (data, history) {
// use response from each to populate data object literal. Something like this? :
json.name = data.name
json.last_login = history.last_login
}));