如何从中获取特定密钥?

时间:2018-12-31 15:12:37

标签: javascript object

我过去曾经使用过hasOwnPropertytypeof,但是这个让我很沮丧... 我试图获取所有具有匹配键的键,以便将它们与其他键示例配对:

{"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   :   
}]}

很明显strIngredient1strMeasure1等匹配... 任何建议或帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

解释

在此示例中,您可以看到我分两部分提供了解决方案,其中一种是一种简单的方法,可以简单地从膳食中获取'x'成分,然后是另一种解决方案,它将遍历整个膳食用餐,打印出每种成分。

正如我在解决方案中所述,您可以使用forEach,或者,也可以使用mapreduce之类的函数。如果您不知道何时使用哪种算法,基本经验法则是,如果您希望遵循函数式编程,请使用mapreduce概念。 forEach解决方案使副作用更容易发生,等等。。。我的意思是这在一定程度上值得商de,但这仍然是基本思想……

编辑

我为这个演示提供了一个简单的日志功能,长话短说,当您运行此代码片段时,我个人觉得这很讨厌为控制台窗口提供的空间太小,因此在以后每次记录一件事一些延迟,并清除控制台。

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');

答案 1 :(得分:0)

对于那些有兴趣或是否有帮助的人来说,这里是最终产品!所有排列整齐,易于使用! :)再次谢谢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");