如何使用JavaScript搜索JSON树

时间:2015-03-03 16:53:20

标签: javascript json

这里有一个JSON树:

{  
       "title":"Recipe Puppy",
       "version":0.1,
       "href":"http:\/\/www.recipepuppy.com\/",
       "results":[  
          {  
             "title":"Ginger Champagne",
             "href":"http:\/\/allrecipes.com\/Recipe\/Ginger-Champagne\/Detail.aspx",
             "ingredients":"champagne, ginger, ice, vodka",
             "thumbnail":"http:\/\/img.recipepuppy.com\/1.jpg"
          },
          {  
             "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":"ginger, brown sugar, butter, butter, powdered sugar, eggs, flour, nutmeg, rum, salt, vanilla extract, sugar",
             "thumbnail":"http:\/\/img.recipepuppy.com\/3.jpg"
          }
        ]
}

我需要对其进行搜索,以便title({1}}中的搜索词例如是“姜”

这是我尝试做的事情:

ingredients

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用Array的filter方法:

...
var filter = data.results.filter(function (el) {
    return el[searchField].indexOf(searchVal) >= 0;
});
if (filter.length) ourResults = filter;