将数组从JSON映射到引导表

时间:2016-11-22 17:22:15

标签: javascript jquery html json ajax

如何将此JSON文件中的数组列出到表中?我可以有单个值,如标题出现查找,但当我尝试调用result.ingredients [index]我得到undefined?香港专业教育学院尝试过result.recipe.ingredients [index],但它仍未定义,并且我在网上找到的关于如何做到这一点很少?

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"

1 个答案:

答案 0 :(得分:0)

如果您试图遍历各个成分并列出它们,则可能需要简单的每个循环

编辑:使用每个

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

使用地图

success: function(result) {                           
  var msg = 
  $.map(result.ingredients, function (ingredient, index) {
        return '<tr><td>' + result.title+ '</td><td>' + ingredient + '</td></tr>';
  }).join();
  $('#location').append(msg);      
}