gpt4 book ai didi

javascript - 如何使用 JavaScript 搜索 JSON 树

转载 作者:行者123 更新时间:2023-11-28 00:32:35 28 4
gpt4 key购买 nike

这里我们有一个 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 (菜谱)如果搜索词在 ingredients例如“姜”

这是我尝试做的:

  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]);
}

谢谢!

最佳答案

您可以使用数组的 filter方法:

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

关于javascript - 如何使用 JavaScript 搜索 JSON 树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28837427/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com