【问题标题】:Mapping through an array of objects error - javascript通过对象数组映射错误 - javascript
【发布时间】:2020-10-24 21:37:49
【问题描述】:

我正在尝试映射从第三方 api 返回的对象数组以返回某些对象值,但我的 map 函数存在错误,我无法找出原因。我已经测试以确保我的其余代码的行为正常,只是这一个地图功能我似乎无法正常工作。

这是我当前的代码:

async function displayRecipeCard(inputString) {
 
 const recipes = await getRecipeInfo(inputString); //fetches data from api and returns an object
 const recipeResults = recipes.results; // returns an array of objects

 const recipeCard = recipeResults.map(recipe => {
   return recipe.title; 
 });
};

返回:

[[PromiseStatus]]: "resolved"
[[PromiseValue]]: undefined

现在如果我写:

async function displayRecipeCard(inputString) {
  const recipes = await getRecipeInfo(inputString);
  const recipeResults = await recipes.results;
  
  return recipeResults[0].title;
};

按预期返回第一个数组对象元素的标题:

[[PromiseStatus]]: "resolved"
[[PromiseValue]]: undefined

任何人都可以注意到我的代码中的任何错误或知道问题可能是什么吗?

谢谢!

【问题讨论】:

  • 您是说recipeCard 的值是解析为未定义的承诺吗?或者你是说对displayRecipeCard() 的调用是在给出一个解析为未定义的承诺?如果是 displayRecipeCard(),那是因为您没有从 displayRecipeCard 函数返回任何内容

标签: javascript arrays object array.prototype.map


【解决方案1】:

根据您所说的,results 似乎是一个承诺。所以你需要等待这个承诺,然后map 它实现的数组:

async function displayRecipeCard(inputString) {
    const recipes = await getRecipeInfo(inputString);
    //              ^^^^^−−−−− you'll want to double-check that this is necessary
    const recipeResults = await recipes.results;
    //                    ^^^^^−−−−− looks like you need this one though
   
    const recipeCard = recipeResults.map(({title}) => title); // Your original was fine, but this shows using destructuring if you like
} // Note: No `;` on function declarations

从根本上说,您需要检查getReceiptInfo 的文档(或实现)以确定它返回什么,然后在执行map 之前检查await 任何承诺。

【讨论】:

  • (哎呀!编辑错误。如果您在上面两次看到“您需要仔细检查是否有必要”,请点击刷新。)
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 2019-11-21
  • 2022-01-25
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
相关资源
最近更新 更多