Conor T Conor T - 13 days ago 8
Javascript Question

Mapping an array from JSON to a bootstrap table

How do I list the Array in this JSON file to the table? I can have single values like title appear find but when I try call result.ingredients[index] I get undefined? ive tried result.recipe.ingredients[index] too but its still undefined and theres very little online I can find on how to do this?

var result = [];


$.ajax({
url: 'https://community-food2fork.p.mashape.com/get?key=0ee5a01caf7f7c3512b54978628f1a4e&rId=37859', // The URL to the API. You can get this in the API page of the API you intend to consume
type: 'GET', // The HTTP Method, can be GET POST PUT DELETE etc
data: {}, // Additional parameters here
dataType: 'json',
success: function(data) {
result = JSON.parse(JSON.stringify(data.recipe));
console.dir(result.ingredients);
$('#location').append($.map(result, function (ignore, index) {
return '<tr><td>' + result.title+ '</td><td>' + result.ingredients[index] + '</td></tr>';
}).join());
},
error: function(err) { alert(err); },
beforeSend: function(xhr) {
xhr.setRequestHeader("X-Mashape-Authorization", "KEY"); // Enter here your Mashape key
}
});


JSON:

Object
f2f_url:
"http://food2fork.com/view/37859"
image_url:
"http://static.food2fork.com/chickenturnover2_300e6667e66.jpg"
ingredients:
Array[6]
0:
"1 1/2 cups shredded rotisserie chicken"
1:
"1 1/2 cups grated Gruyre"
2:
"1 cup frozen peas"
3:
"2 sheets (one 17.25-ounce package) frozen puff pastry, thawed"
4:
"1 large egg, beaten"
5:
"1/4 cup Dijon mustard↵"
length:
6
__proto__
:
Array[0]
publisher
:
"Real Simple"
publisher_url
:
"http://realsimple.com"
recipe_id
:
"37859"
social_rank
:
99.84842829206659
source_url
:
"http://www.realsimple.com/food-recipes/browse-all-recipes/chicken-and-gruyere-turnovers-00000000052482/index.html"
title
:
"Chicken and Gruyre Turnovers"

Answer

If you are trying to iterate through the ingredients and list them, you may need simple each loop

success: function(result) {                           
  var msg ='';
  $.each(result.ingredients, function (k, v) {
        msg = msg+ '<tr><td>' + result.title+ '</td><td>' + v + '</td></tr>';
  }));
  $('#location').append(msg);      
}
Comments