Chris
Chris

Reputation: 944

How to search JSON tree with JavaScript

Here we have a JSON tree:

{  
       "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"
          }
        ]
}

I need to make a search through it so I will get the title (of the recipe) if the search word in ingredients is for example "ginger"

Here is what I tried to do:

  var url = requestUrl("http://www.recipepuppy.com/api/");
  var data = JSON.parse(url);

  var ourResults = [];
  var searchField = "ingredients";
  var searchVal = "onions";
  for (var i=0 ; i < data.results.length ; i++)
  {
      if (data.results[i][searchField] == searchVal) {
          ourResultss.push(data.results[i]);
      }

Thank you!

Upvotes: 1

Views: 453

Answers (1)

hindmost
hindmost

Reputation: 7195

You could use Array's filter method:

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

Upvotes: 1

Related Questions