如何在对象数组上使用 Promise.all,然后将它们重新分配给新对象中的相关键?

Phi*_*hoi 4 javascript reactjs

我有点卡在代码的中间部分。我知道我想要的结局和开始是什么样子,但似乎无法填补空白。

我调用fetch4 个 API 端点,并将其存储Promises到相关密钥中,该密钥告诉我它们是什么。

然后我使用循环遍历所有这些for in,并将所有这些推Promises入一个数组中,以便我可以调用Promise.all它们。

将数组成功记录到控制台后,我现在看到数组中充满了包含我的数据的对象。但是,我无法判断哪些数据属于哪个对象键,就像原始对象一样

有一个更好的方法吗?我确实知道我想在这段代码中使用这个事实Promise.all;这是我不想让步的事情,因为我正在努力弄清楚如何在不放弃的情况下使这成为可能(现在已经这样做了几个小时)。

在我的代码末尾(这只是我的 React 应用程序中真实示例的伪代码),我只想获取最终对象,并将其推送到state.

任何帮助表示赞赏。

//imitating React State as an example
const state = {
  iliakan: '',
  remy: '',
  jeresig: '',
}

//put all of the urls in an object with a key-pair value to describe the data
const githubAPI = {
  iliakan: 'https://api.github.com/users/iliakan',
  remy: 'https://api.github.com/users/remy',
  jeresig: 'https://api.github.com/users/jeresig'
}

//create an empty object to assign promises to keys
const movieData = {};
const promiseArr = [];
//store promise into relevant key
for (const user in githubAPI) {
  movieData[user] = fetch().then(res => res.json())
}
//now movieData has keys with values set to related Promises
console.log(movieData);
//loop through these promises, and put them in an Array for Promise.all
for (const userData in movieData) {
  promiseArr.push(movieData[userData])
}

//Use Promise.all on all of those promises
Promise.all(promiseArr).then(responseArr => console.log(responseArr);

//this is where I am stuck. I now have an array of objects with all the correct data, but I don't know how to reassign them back to their original, matching key that they had in the movieData object!


//end goal is to have an object like this
//const movieData = {
//  iliakan: {//object with data from api},
//  remy: {//object with data from api},
//  jeresig: {//object with data from api}
//}

//use the movieData to setState and update current component state
Run Code Online (Sandbox Code Playgroud)

Mic*_*ral 6

实现此目的的一种方法是将“键和属性之间的连接”视为编程中自己的“事物”:键值对。javascript API 将它们称为“条目”,并使用一个简单的 2 元素数组作为“事物”:['key', 'value']将是key: 'value'

您可以使用 来从对象转到条目Object.entries(the_object)。它将返回一个其中包含“entry-array”-s 的数组:

const githubAPI = {
  iliakan: 'https://api.github.com/users/iliakan',
  remy: 'https://api.github.com/users/remy',
  jeresig: 'https://api.github.com/users/jeresig'
}

let githubEntries = Object.entries(githubAPI)
// githubEntries = [
//   ['iliakan', 'https://api.github.com/users/iliakan'],
//   ['remy', 'https://api.github.com/users/remy'],
//   ['jeresig', 'https://api.github.com/users/jeresig'],
// ]
Run Code Online (Sandbox Code Playgroud)

现在您可以使用这个概念,并使 Promise 也成为“条目”,将结果和键组合在一个[key, value]数组中。这样,您以后就可以根据Promise.all结果中的条目重建对象。

let promiseOfEntries = Promise.all(Object.entries(githubAPI).map((entry) => {
  let [key, value] = entry;
  return fetch().then(x => x.json()).then(result => {
    // Important step here: We combine the result with the key,
    // into a new [key, value] entry
    return [key, result];
  })
}

let promiseOfResults = promiseOfEntries.then(resultEntries => {
  // From the "entries", we build an object again here
  let results = {};
  for (let [key, value] of resultEntries) {
    results[key] = value;
  }
  return results;
});

promiseOfResults.then(results => {
  // Do anything with results!
  console.log('results:', results);
});
Run Code Online (Sandbox Code Playgroud)

Lodash 甚至必须_.fromPairs这样做[ [key, value], [key2, value2], ...]才能进行{ key: value, key2: value2 }转换。 https://lodash.com/docs/4.17.11#fromPairs

您可以在任何需要在对象和数组之间切换的地方使用“条目”的概念。

希望我解释得足够好,如果我没有解释清楚,请不要害怕在评论中提问!