这里有一个JSON文件:
[
{
"title":"Potato and Cheese Frittata",
"href":"http://allrecipes.com/Recipe/Potato-and-Cheese-Frittata/Detail.aspx",
"ingredients":"cheddar cheese, eggs, olive oil, onions, potato, salt",
"thumbnail":"http://img.recipepuppy.com/2.jpg"
},
{
"title":"Eggnog Thumbprints",
"href":"http://allrecipes.com/Recipe/Eggnog-Thumbprints/Detail.aspx",
"ingredients":"brown sugar, butter, butter, powdered sugar, eggs, flour, nutmeg, rum, salt, vanilla extract, sugar",
"thumbnail":"http://img.recipepuppy.com/3.jpg"
},
{
"title":"Irish Champ",
"href":"http://allrecipes.com/Recipe/Irish-Champ/Detail.aspx",
"ingredients":"black pepper, butter, green onion, milk, potato, salt",
"thumbnail":"http://img.recipepuppy.com/5.jpg"
},
{
"title":"Chocolate-Cherry Thumbprints",
"href":"http://allrecipes.com/Recipe/Chocolate-Cherry-Thumbprints/Detail.aspx",
"ingredients":"cocoa powder, baking powder, butter, eggs, flour, oats, salt, sugar, vanilla extract",
"thumbnail":"http://img.recipepuppy.com/6.jpg"
},
{
"title":"Hot Spiced Cider",
"href":"http://allrecipes.com/Recipe/Hot-Spiced-Cider/Detail.aspx",
"ingredients":"allspice, apple cider, brown sugar, cinnamon, cloves, nutmeg, orange, salt",
"thumbnail":"http://img.recipepuppy.com/8.jpg"
}
]
我如何才能获得每个titles
的{{1}}
例如,我只需要(马铃薯和奶酪蛋饼,蛋酒指纹,巧克力樱桃指纹,热香料苹果酒)
谢谢!
答案 0 :(得分:1)
<强> jsFiddle Demo
强>
首先,JSON是用于序列化信息的字符串表示法。它可以反序列化(在JavaScript中解析)为对象或数组。你所拥有的是反序列化的格式,因此它只是一个简单的对象数组。
因此,本机.map
MDN api函数可以将每个对象的.title映射到只有这些标题的数组中。
var titles = result.map(function(obj){ return obj.title; });
答案 1 :(得分:0)
试试这个它会给你你想要的东西:
var a = [{ "title":"Potato and Cheese Frittata"}, {"title":"Eggnog Thumbprints" }];
for (var i = 0; i < a.length; i++) {
alert(a[i].title);
}