簡體   English   中英

如何使用 JavaScript 從 JSON 中獲取值

[英]How to get a value from JSON using JavaScript

這里我們有一個 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"
   }
]

我怎樣才能只得到每個resultstitles ,例如這里我只需要得到(土豆和奶酪煎蛋餅、蛋酒指紋、巧克力櫻桃指紋、辣味蘋果酒)

謝謝!

jsFiddle Demo

首先,JSON 是用於序列化信息的字符串表示法。 它可以反序列化(在 JavaScript 中解析)為對象或數組。 您擁有的是反序列化格式,因此它只是一個簡單的對象數組。

因此,原生的.map MDN api 函數將把每個對象的 .title 映射到一個包含這些標題的數組中。

var titles = result.map(function(obj){ return obj.title; });

試試這個它會給你你想要的:

var a = [{ "title":"Potato and Cheese Frittata"}, {"title":"Eggnog Thumbprints" }]; 
for (var i = 0; i < a.length; i++) { 
    alert(a[i].title); 
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM