【问题标题】:How can I filter out the similar attribute names in an array in Javascript?如何在Javascript中过滤掉数组中相似的属性名称?
【发布时间】:2021-08-16 10:08:37
【问题描述】:

我正在做一个从 API 中提取数据的项目,到目前为止一切顺利,但我似乎无法弄清楚如何具体过滤掉成分和测量值。

数组如下所示:

{
  "idMeal": "52977",
  "strMeal": "Corba",
  "strDrinkAlternate": null,
  "strCategory": "Side",
  "strArea": "Turkish",
  "strInstructions": "",
  "strMealThumb": "https://www.themealdb.com/images/media/meals/58oia61564916529.jpg",
  "strTags": "Soup",
  "strYoutube": "https://www.youtube.com/watch?v=VVnZd8A84z4",
  "strIngredient1": "Lentils",
  "strIngredient2": "Onion",
  "strIngredient3": "Carrots",
  "strIngredient4": "Tomato Puree",
  "strIngredient5": "Cumin",
  "strIngredient6": "Paprika",
  "strIngredient7": "Mint",
  "strIngredient8": "Thyme",
  "strIngredient9": "Black Pepper",
  "strIngredient10": "Red Pepper Flakes",
  "strIngredient11": "Vegetable Stock",
  "strIngredient12": "Water",
  "strIngredient13": "Sea Salt",
  "strIngredient14": "",
  "strIngredient15": "",
  "strIngredient16": "",
  "strIngredient17": "",
  "strIngredient18": "",
  "strIngredient19": "",
  "strIngredient20": "",
  "strMeasure1": "1 cup ",
  "strMeasure2": "1 large",
  "strMeasure3": "1 large",
  "strMeasure4": "1 tbs",
  "strMeasure5": "2 tsp",
  "strMeasure6": "1 tsp ",
  "strMeasure7": "1/2 tsp",
  "strMeasure8": "1/2 tsp",
  "strMeasure9": "1/4 tsp",
  "strMeasure10": "1/4 tsp",
  "strMeasure11": "4 cups ",
  "strMeasure12": "1 cup ",
  "strMeasure13": "Pinch",
  "strMeasure14": " ",
  "strMeasure15": " ",
  "strMeasure16": " ",
  "strMeasure17": " ",
  "strMeasure18": " ",
  "strMeasure19": " ",
  "strMeasure20": " ",
  "strSource": "https://findingtimeforcooking.com/main-dishes/red-lentil-soup-corba/",
  "strImageSource": null,
  "strCreativeCommonsConfirmed": null,
  "dateModified": null
}

我想专门取出所有包含“strIngredient”的属性名称并将它们全部放入一个单独的数组中,与“strMeasure”相同。

const query = async function () {
  try {
    const response = await fetch(
      "https://www.themealdb.com/api/json/v1/1/search.php?s="
    );
    const data = await response.json();
    console.log(data);

    data.meals.forEach((recipe) => {
      const recipeName = recipe.strMeal;
      const recipeImage = recipe.strMealThumb;
      const recipeRegion = recipe.strArea;
      const recipeCategory = recipe.strCategory;
      const recipeInstructions = recipe.strInstructions;
      const recipeLink = recipe.strSource;
    });
  } catch (error) {
    console.log(error);
  }
};

任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 你已经有循环了,只要通过正则表达式检查key是否包含“strIngredient”即可。如果它确实把它放在一个数组中。您几乎已经描述了自己如何做到这一点。
  • 是的,我知道如何做的大致思路,只是不知道如何应用它。我不知道该使用哪种数组方法。

标签: javascript arrays list sorting filter


【解决方案1】:

请参阅下面的代码。您将在ingredients 数组中的所有strIngredientsmeasures 数组中的所有strMeasure

const query = async function () {
    try {
        const response = await fetch(
            "https://www.themealdb.com/api/json/v1/1/search.php?s="
        );
        const data = await response.json();
        console.log(data);

        data.meals.forEach((recipe) => {
            const recipeName = recipe.strMeal;
            const recipeImage = recipe.strMealThumb;
            const recipeRegion = recipe.strArea;
            const recipeCategory = recipe.strCategory;
            const recipeInstructions = recipe.strInstructions;
            const recipeLink = recipe.strSource;
            const ingredients = Object.keys(recipe).filter(k => k.includes('strIngredient')).map(k => recipe[k]);
            const measures = Object.keys(recipe).filter(k => k.includes('strMeasure')).map(k => recipe[k]);
        });
    } catch (error) {
        console.log(error);
    }
};

【讨论】:

  • 在 forEach 中创建变量是否明智?它们不仅可以在该范围内访问吗?
【解决方案2】:
const strIngredient = Object.keys(data.meals)
  .filter(x => x.includes('strIngredient'))
  .reduce((acc, key) => {
    acc[key] = data.meals[key]
  }, [])

const strMeasure = Object.keys(data.meals)
  .filter(x => x.includes('strMeasure'))
  .reduce((acc, key) => {
    acc[key] = data.meals[key]
  }, [])

【讨论】:

    【解决方案3】:

    这会使用来自其 Feed 的所有数据构建配方,但会将成分和测量值移动到它们自己的数组中

    let recipes = []
    
    const query = async function() {
      try {
        const response = await fetch(
          "https://www.themealdb.com/api/json/v1/1/search.php?s="
        );
        const data = await response.json();
        // console.log(data);
        //"strIngredient" and put those all into a separate array, and same with "strMeasure".
        data.meals.forEach((recipe) => {
          let newRecipe = {
            ingredients: [],
            measurements: []
          }
          //console.log(recipe)
          for (const [key, value] of Object.entries(recipe)) {
    
            let pair = {};
            pair[key] = value;
            if (key.indexOf('strIngredient') !== -1) newRecipe.ingredients.push(pair);
            else if (key.indexOf('strMeasure') !== -1) newRecipe.measurements.push(pair);
            else newRecipe[key] = value;
          }
          recipes.push(newRecipe)
        });
    
        console.log(recipes)
    
      } catch (error) {
        console.log(error);
      }
    };
    
    query()

    【讨论】:

      猜你喜欢
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 2022-12-06
      • 2012-05-17
      • 1970-01-01
      • 2020-02-24
      相关资源
      最近更新 更多