输入:用户名字符串数组
需要的输出:对应于输入中每个用户名的 Javascript 对象数组。这些 JS 对象的属性将从每个用户名的两个 API 调用构建(我正在使用 $.getJSON
调用。欢迎提出建议)。
我有一组用于 Twitch API 的用户名:
let users = ["OgamingSC2", "storbeck", "comster404"] // actual list is longer
我想使用 Array.prototype.map()用于创建对象数组的高阶函数,如
let userObjects = [ {...}, {...}, {...}, ... ]
每个对象看起来像:
{
username: 'storbeck' // <-- Added by me
stream: null, // <-- Added by first API call
_links: { // <-- Added by first API call
self:'https://api.twitch.tv/kraken/streams/storbeck',
channel:'https://api.twitch.tv/kraken/channels/storbeck'
}
logo: 'http:// ... png' // <-- Added by second API call
}
这是返回 $.getJSON
Promise 的两个 API 调用函数:
let getStreamInfo = (username) => {
return $.getJSON('https://api.twitch.tv/kraken/streams/'+username+'?callback=?')
.then((x) => x) // should I include this then?
}
let getUserInfo = (twitchObject) => {
return $.getJSON('https://api.twitch.tv/kraken/users/'+ twitchObject.user )
}
到目前为止,我的代码中没有产生预期对象的是:
let userObjects = users.map((user)=>{
return getStreamInfo(user)
.done((data) => {
let result = {
username: user,
data: data
}
console.log(JSON.stringify(result)) // prints out the intended object so far
return result
})
})
现在当我打印出 userObjects
的内容时,我得到:
"{}"
"{}"
"{}"
// ... and so on
更进一步,我想链接 userObjects
并从我在 getUserInfo
函数中获得的任何内容向每个 JS 对象添加更多内容。
我想深入探讨如何使用函数式 Javascript 完成此操作,但这不是必需的。
最佳答案
您的方法是正确的,您只需要对函数进行少量修改。
let getStreamInfo = (username) => {
return $.getJSON('https://api.twitch.tv/kraken/streams/'+username+'?callback=?');
}
let getUserInfo = (user) => {
return $.getJSON('https://api.twitch.tv/kraken/users/'+ user);
}
let userObjects = [];
核心功能需要 Promise 同步:
users.map((user)=>{
Promise.all(getStreamInfo(user), getUserInfo(user)).then((data)=>{
let obj = {
username: user,
stream: data[0].stream,
_links: data[0]._links,
logo: data[1].logo
}
userObjects.push(obj);
});
});
关于javascript - 使用两个中间 $.getJSON 调用将字符串数组转换为对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36442469/