我正在学习和做一个使用Reaction钩子的项目.这是一款菜谱应用程序,使用的API来自MealDB.

在本例中有多个成分,每个成分来自API中不同的键,比如从strIngredient1到strIngredient20.我想将它们全部放在一个数组中,这样我就可以使用贴图将它们全部呈现在一个列表中.这里有一个例子说明了它是如何实现的:

    const { strIngredient1, strIngredient2, strIngredient3, strIngredient4,
      strIngredient5, strIngredient6, strIngredient7, strIngredient8, strIngredient9,
      strIngredient10, strIngredient11, strIngredient12, strIngredient13, strIngredient14,
      strIngredient15, strIngredient16, strIngredient17, strIngredient18, strIngredient19,
      strIngredient20 } = recipeIdState;

    const ingredientArray = [strIngredient1, strIngredient2, strIngredient3,
      strIngredient4, strIngredient5, strIngredient6,
      strIngredient7, strIngredient8, strIngredient9,
      strIngredient10, strIngredient11, strIngredient12, strIngredient13, strIngredient14,
      strIngredient15, strIngredient16, strIngredient17, strIngredient18, strIngredient19,
      strIngredient20];
    setIngredients(ingredientArray);

我觉得没有必要使用这么多空间来创建一个简单的数组,所以我的问题是,我是否可以使用for来命名这些值并将它们放入ReceipeIdState变量中?

我的 idea 是这样的:

for(let i = 1; i <= 20, i++) {
  const { `strIngredient${i}`} = recipeIdState;
  ingredientArray.push(`strIngredient${i}`);
}
  setIngredients(ingredientArray)

我try 使用简单的Java脚本解构来创建一个具有多个值的简单数组,但我觉得这不是编写干净代码的最佳方式.

推荐答案

假设您获得了API响应JSON,并将其放入自己的变量中,将其命名为data.然后,您可以在data上使用filter()来仅查找这些以strIngredient开头的键,并将它们提取到单独的数组中以备将来使用.

let data = {
  "strIngredient1": "apple",
  "strIngredient2": "chocolate",
  "strIngredient3": "honey",
  "strIngredient4": "carrots",
  "strCategory": "cakes",
  "strInstructions": "....",
  "strDrinkAlternate":null
};

let ingredients = Object.keys(data).filter(function(key) {
  return key.startsWith("strIngredient");
}).reduce(function(obj, key) {
  obj[key] = jsonObject[key];
  return obj;
}, {});

console.log(ingredients); 
// Output: { "strIngredient1": "apple", "strIngredient2": "chocolate", "strIngredient3": "honey", "strIngredient4": "carrots" }

在此之后,当然可以执行所有classic 的JSON.parse()操作将其转换为array.

Javascript相关问答推荐

使用axios.获取实时服务器时的404响应

浮动Div的淡出模糊效果

WebRTC关闭navigator. getUserMedia正确

康威的生活游戏规则在我的Javascript版本中不起作用.''我做错了什么?

查询参数未在我的Next.js应用路由接口中定义

Use Location位置成员在HashRouter内为空

使用Nuxt Apollo在Piniastore 中获取产品细节

钛中的onClick事件需要在两次点击之间等待几秒钟

如何在HTMX提示符中设置默认值?

未捕获的运行时错误:调度程序为空

如何用javascript更改元素的宽度和高度?

ComponentWillReceiveProps仍在React 18.2.0中工作

使用Perl Selify::Remote::Driver执行Java脚本时出错

如何在Reaction中设置缺省值, Select 下拉列表,动态追加剩余值?

有角粘桌盒阴影

将字体样式应用于material -UI条形图图例

当S点击按钮时,我如何才能改变它的样式?

不允许在对象文本中注释掉的属性

鼠标进入,每秒将图像大小减小5%

如何在预览中显示html+css与数据URL?