Как я могу получить конкретные ключи от этого? - PullRequest
0 голосов
/ 31 декабря 2018

Я использовал hasOwnProperty и typeof в прошлом, но этот вводит меня в заблуждение ... Я пытаюсь получить все ключи, у которых есть совпадающие ключи, чтобы я мог соединить их с другими примерами ключей:

{"meals": [{    
  strIngredient1  : lemons
  strIngredient2    :   paprika
  strIngredient3    :   red onions
  strIngredient4    :   chicken thighs
  strIngredient5    :   vegetable oil
  strMeasure1   :   2 Juice
  strMeasure2   :   4 tsp
  strMeasure3   :   2 finely chopped
  strMeasure4   :   16 skinnless
  strMeasure5   :   
}]}

Очевидно, что strIngredient1 совпадает с strMeasure1 и т. Д. Любые предложения или помощь будут с благодарностью!

Ответы [ 2 ]

0 голосов
/ 01 января 2019

Для тех, кто заинтересован или если кому-то это поможет, вот конечный продукт!Все аккуратно и аккуратно в одном массиве, прост в использовании!:) Еще раз спасибо JO3-W3B-D3V!

getRecipe: function(url) {
    request({
        url: url,
        method: 'GET'
    }, (error, response, body) => {
        if (!error && response.statusCode == 200) { 
            var result = JSON.parse(body);  
            //console.log(result);

             // Just some TESTING.
      var meals = result.meals;  //returns array
      var meal = meals[0]; // returns object
       //console.log(meal);
      // Start here to rename keys and match them to the ingredients.
      const newArray = meals.reduce((array, meal) => {
          // Rather than iterate over ALL of the keys, just 
          // do this, basically 50% of the keys. 
          const subArray = Object.keys(meal).filter(key => key.indexOf('strIngredient' == -1));
         // console.log(subArray);
          // Basically add some ojects to the array.
          subArray.forEach(key => {
              const int = key.replace(/\D/g, '');
              const measureKey = `strMeasure${int}`;
              const ingredientKey = `strIngredient${int}`;

              const obj = {
                  measure: meal[measureKey],
                  ingredient: meal[ingredientKey] 
              };
            //  console.log(obj);  //Testing data before
          if (obj.measure && obj.ingredient != 'undefined' || undefined || "" || null){
              array.push(obj);
            //  console.log(array);  //Testing data after
          }
          });

          const recipeName =  meal.strMeal;
          const instruction = meal.strInstructions;
          const video = meal.strYoutube;
          const thumb = meal.strMealThumb;
          const nation = meal.strArea;
          const category = meal.strCategory;

          const recipe = {recipeName, instruction, video, thumb, nation, category};
          array.push(recipe);
          //console.log(recipe);  Testing full array

          // Make sure to return the array.
          return array;

      }, []);

      // Now just print the resuts, and make sure that you know 
      // and alert that the app has finished.


      console.log(newArray, "FINISHED");
0 голосов
/ 31 декабря 2018

Объяснено

В этом примере вы можете видеть, что я предоставил решение в двух частях, одна из которых представляет собой простой способ простого доступа к 'x' ингредиенту из множества блюд, а затем другое решение, котороебудет перебирать массив блюд, распечатывая каждый отдельный ингредиент.

Как я уже говорил в моем решении, вы можете использовать forEach или, альтернативно, вы также можете использовать такие функции, как map или reduce, если хотите.В случае, когда вы не знаете, когда использовать какое из них, базовое эмпирическое правило означает, что вы будете использовать map или reduce, если хотите следовать принципам функционального программирования.forEach решение позволяет побочные эффекты происходить более легко, и т.д ... Я имею в виду это спорно в определенной степени, но это основная идея в любом случае ...

1015 * Редактировать 1017 *Я включил простую функцию журнала для этой демонстрации, если коротко, когда вы запускаете этот фрагмент кода, лично я нахожу отвратительным то, как мало места предоставляется для окна консоли, поэтому регистрируйте одну вещь за раз после некоторой задержки иочистите консоль тоже.

let delay = 0;
const DELAY_INC = 1500;

// Just for this demo, have the ability to log something, 
// after a delay and clear the console.
const log = (arg, alrt) => {
  setTimeout(() => {
    console.clear();
    console.log(arg);
    if (alrt != null) {
      alert(alrt);
    }
  }, delay);
  delay += DELAY_INC;
};

// Your data.
var data = {
  "meals": [{
    strIngredient1: 'lemons',
    strIngredient2: 'paprika',
    strIngredient3: 'red onions',
    strIngredient4: 'chicken thighs',
    strIngredient5: 'vegetable oil',
    strMeasure1: '2 Juice',
    strMeasure2: '4 tsp',
    strMeasure3: '2 finely chopped',
    strMeasure4: '16 skinnless',
    strMeasure5: ''
  }]
};

// Just some demo.
var meals = data.meals;
var meal = meals[0];
var ingredient = meal.strIngredient1;

log(data); // Log the raw data.
log(meals); // Log the array of meals.
log(meal); // Log a specific meal.
log(ingredient); // Log a specific ingredient.

// If you wish to iterate, log each ingredient for each meal. 
data.meals.forEach(meal => Object.keys(meal).forEach(key => log(meal[key])));

// Here's a solution.
const newArray = data.meals.reduce((array, meal) => {
  // Rather than iterate over ALL of the keys, just 
  // do this, basically 50% of the keys. 
  const subArray = Object.keys(meal).filter(key => key.indexOf('strIngredient' == -1));

  // Basically add some ojects to the array.
  subArray.forEach(key => {
    const int = key.replace(/\D/g, '');
    const measureKey = `strMeasure${int}`;
    const ingredientKey = `strIngredient${int}`;

    const obj = {
      ingredient: meal[ingredientKey],
      measure: meal[measureKey]
    };

    array.push(obj);
  });

  // Make sure to return the array.
  return array;
}, []);

// Now just print the resuts, and make sure that you know 
// and alert that the app has finished. 
log(newArray, 'FINISHED');
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...