Извлечение данных из объекта JSON с похожими ключами - PullRequest
0 голосов
/ 08 февраля 2020

У меня есть JSON данные, которые возвращаются из запроса AJAX GET. Этот запрос возвращает различные наборы блюд и способы их приготовления, включая необходимые ингредиенты и их измерения. Фрагмент JSON данных (некоторые ключи: значение было удалено для удобства просмотра):

{
  "idMeal":"52768",
  "strMeal":"Apple Frangipan Tart",
  "strDrinkAlternate":null,
  "strCategory":"Dessert",
  "strIngredient1":"digestive biscuits",
  "strIngredient2":"butter",
  "strIngredient3":"Bramley apples",
  "strIngredient4":"butter, softened",
  "strIngredient5":"caster sugar",
  "strIngredient6":"free-range eggs, beaten",
  "strIngredient7":"ground almonds",
  "strIngredient8":"almond extract",
  "strIngredient9":"flaked almonds",
  "strIngredient10":"",
  "strIngredient11":"",
  "strIngredient12":"",
  "strIngredient13":"",
  "strIngredient14":"",
  "strIngredient15":"",
  "strIngredient16":null,
  "strIngredient17":null,
  "strIngredient18":null,
  "strIngredient19":null,
  "strIngredient20":null,
  "strMeasure1":"175g\/6oz",
  "strMeasure2":"75g\/3oz",
  "strMeasure3":"200g\/7oz",
  "strMeasure4":"75g\/3oz",
  "strMeasure5":"75g\/3oz",
  "strMeasure6":"2",
  "strMeasure7":"75g\/3oz",
  "strMeasure8":"1 tsp",
  "strMeasure9":"50g\/1\u00beoz",
  "strMeasure10":"",
  "strMeasure11":"",
  "strMeasure12":"",
  "strMeasure13":"",
  "strMeasure14":"",
  "strMeasure15":"",
  "strMeasure16":null,
  "strMeasure17":null,
  "strMeasure18":null,
  "strMeasure19":null,
  "strMeasure20":null
},
{
  "idMeal":"52893",
  "strMeal":"Apple & Blackberry Crumble",
  "strDrinkAlternate":null,
  "strCategory":"Dessert",
  "strIngredient1":"Plain Flour",
  "strIngredient2":"Caster Sugar",
  "strIngredient3":"Butter",
  "strIngredient4":"Braeburn Apples",
  "strIngredient5":"Butter",
  "strIngredient6":"Demerara Sugar",
  "strIngredient7":"Blackberrys",
  "strIngredient8":"Cinnamon",
  "strIngredient9":"Ice Cream",
  "strIngredient10":"",
  "strIngredient11":"",
  "strIngredient12":"",
  "strIngredient13":"",
  "strIngredient14":"",
  "strIngredient15":"",
  "strIngredient16":"",
  "strIngredient17":"",
  "strIngredient18":"",
  "strIngredient19":"",
  "strIngredient20":"",
  "strMeasure1":"120g",
  "strMeasure2":"60g",
  "strMeasure3":"60g",
  "strMeasure4":"300g",
  "strMeasure5":"30g",
  "strMeasure6":"30g",
  "strMeasure7":"120g",
  "strMeasure8":"\u00bc teaspoon",
  "strMeasure9":"to serve",
  "strMeasure10":"",
  "strMeasure11":"",
  "strMeasure12":"",
  "strMeasure13":"",
  "strMeasure14":"",
  "strMeasure15":"",
  "strMeasure16":"",
  "strMeasure17":"",
  "strMeasure18":"",
  "strMeasure19":"",
  "strMeasure20":""
}

JAVASCRIPT / JQUERY CODE

$.each($(response), function(key, val) {
      let mealName = val.strMeal;
      let mealCategory = val.strCategory;
      let mealInstructions = val.strInstructions;
      let mealIngredient1 = val.strIngredient1;
      let mealIngredient2 = val.strIngredient2;
      ... // Variables continued
      ...
      let mealIngredient20 = val.strIngredient20;

      let mealMeasure1 = val.strMeasure1;
      let mealMeasure2 = val.strMeasure2;
      ... // Variables continued
      ...
      let mealMeasure20 = val.strMeasure20;

      console.log(mealName);
      console.log(mealCategory);
      console.log(mealInstructions);
      console.log(mealIngredient1);
      console.log(mealIngredient2);
      console.log(mealMeasure1);
      console.log(mealMeasure2);
    });

As Вы можете видеть, что каждый прием пищи может содержать до 20 ингредиентов и измерений и будет отличаться друг от друга. Итак, мой вопрос заключается в том, существует ли лучший или более эффективный способ получения каждого ингредиента и измерения, чем мой метод получения каждого из них и сохранения в отдельной переменной, а также избавления от нулевых или пустых переменных, которые не будут использоваться?

Ответы [ 3 ]

2 голосов
/ 08 февраля 2020

Оформить Object.entries () и map :

const data = {
  "idMeal":"52768",
  "strMeal":"Apple Frangipan Tart",
  "strDrinkAlternate":null,
  "strCategory":"Dessert",
  "strIngredient1":"digestive biscuits",
  "strIngredient2":"butter",
  "strIngredient3":"Bramley apples",
  "strIngredient4":"butter, softened",
  "strIngredient5":"caster sugar",
  "strIngredient6":"free-range eggs, beaten",
  "strIngredient7":"ground almonds",
  "strIngredient8":"almond extract",
  "strIngredient9":"flaked almonds",
  "strIngredient10":"",
  "strIngredient11":"",
  "strIngredient12":"",
  "strIngredient13":"",
 }
 

// get an array of [key, value] entries from the response
const properties = Object.entries(data);

// filter out the items whose value is empty
const nonEmpty = properties.filter(([_, value]) => value);

// do whatever you need to do with the rest
nonEmpty.map(([name, value]) => console.log(`${name}: ${value}`));

Приведенный выше код можно усилить, используя операции фильтра и карты:

Object.entries(data)
  .filter(([_, value]) => value )
  .map(([key, value]) => console.log( key, value ));

Вы также можете извлекать и / или фильтровать не ингредиент свойства отдельно, если это полезно:

const data = {
  "idMeal": "52768",
  "strMeal": "Apple Frangipan Tart",
  "strDrinkAlternate": null,
  "strCategory": "Dessert",
  "strIngredient1": "digestive biscuits",
  "strIngredient2": "butter",
  "strIngredient3": "Bramley apples",
  "strIngredient4": "butter, softened",
  "strIngredient5": "caster sugar",
  "strIngredient6": "free-range eggs, beaten",
  "strIngredient7": "ground almonds",
  "strIngredient8": "almond extract",
  "strIngredient9": "flaked almonds",
  "strIngredient10": "",
  "strIngredient11": "",
  "strIngredient12": "",
  "strIngredient13": "",
}

// extract a few known properties, and capture the rest in the 'others' variable.
const {idMeal, strMeal, ...others} = data;

Object.entries(others)
  .filter(([_, value]) => value) // no empty values
  .filter(([key]) => key.includes('Ingredient')) // only 'ingredient' items
  .map(([key, value]) => console.log(key, value));
0 голосов
/ 08 февраля 2020

Вы можете использовать деструктуризацию объектов и использовать оператор rest, чтобы получить оставшиеся части.

const data = {
	  "idMeal":"52768",
	  "strMeal":"Apple Frangipan Tart",
	  "strDrinkAlternate":null,
	  "strCategory":"Dessert",
	  "strIngredient1":"digestive biscuits",
	  "strIngredient2":"butter",
	  "strIngredient3":"Bramley apples",
	  "strIngredient4":"butter, softened",
	  "strIngredient5":"caster sugar",
	  "strIngredient6":"free-range eggs, beaten",
	  "strIngredient7":"ground almonds",
	  "strIngredient8":"almond extract",
	  "strIngredient9":"flaked almonds",
	  "strIngredient10":"",
	  "strIngredient11":"",
	  "strIngredient12":"",
	  "strIngredient13":"",
	  "strIngredient14":"",
	  "strIngredient15":"",
	  "strIngredient16":null,
	  "strIngredient17":null,
	  "strIngredient18":null,
	  "strIngredient19":null,
	  "strIngredient20":null,
	  "strMeasure1":"175g\/6oz",
	  "strMeasure2":"75g\/3oz",
	  "strMeasure3":"200g\/7oz",
	  "strMeasure4":"75g\/3oz",
	  "strMeasure5":"75g\/3oz",
	  "strMeasure6":"2",
	  "strMeasure7":"75g\/3oz",
	  "strMeasure8":"1 tsp",
	  "strMeasure9":"50g\/1\u00beoz",
	  "strMeasure10":"",
	  "strMeasure11":"",
	  "strMeasure12":"",
	  "strMeasure13":"",
	  "strMeasure14":"",
	  "strMeasure15":"",
	  "strMeasure16":null,
	  "strMeasure17":null,
	  "strMeasure18":null,
	  "strMeasure19":null,
	  "strMeasure20":null
};

const { idMeal,  strMeal, strDrinkAlternate, strCategory, ...rest } = data;
console.log(rest);
0 голосов
/ 08 февраля 2020

Ваши свойства объекта strIngredient # должны быть массивом strIngredient [], который вы можете динамически перебирать, также используя strMeasure []. Поскольку ваш код написан сейчас, вы устанавливаете множество свойств, которые не являются необходимыми в зависимости от заданного получения ie.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...