我有基本对象,我想搜索标题和描述值并返回找到的对象。在您的帮助之后,我可以将它们输出为HTML。我目前收到语法错误。
在该示例中,我想返回所有包含搜索词“ dog”的对象
var search_term = "dog";
var search_results = [];
var page_json = [{
"page_title": "Display",
"page_url": "/display/",
"page_description": "We display stuff. search this description for the word dog.",
}, {
"page_title": "DRAM",
"page_url": "/dram/",
"page_description": "stuff about dram here",
}, {
"page_title": "TVs",
"page_url": "/tv/",
"page_description": "stuff about tvs here",
},];
$(page_json).each(function(i, value) {
//console.log( value.page_description );
// search for our term in the description AND title values
if ($(value.page_description).contains(search_term)) {
console.log(value);
// put that object into search_results array
}
});
我想得到的答案...
var search_term = "dog";
var search_results = [];
var page_json = [{
"page_title": "Display",
"page_url": "/display/",
"page_description": "search this description for the word dog.",
},{
"page_title": "this title has a dog",
"page_url": "/dram/",
"page_description": "stuff about dram here",
},{
"page_title": "TVs",
"page_url": "/tv/",
"page_description": "stuff about tvs here",
},
];
var search = function(search_term) {
return page_json.filter(function(item) {
// if search term is inside the title OR description
if (item.page_description.indexOf(search_term) !== -1 || item.page_title.indexOf(search_term) !== -1){
return item;
}
})
}
search_results = search(search_term);
console.log(search_results);
答案 0 :(得分:3)
我不确定jquery是如何完成的,但是这是您在JS中的操作方式:
const foundObject = page_json.find(obj=>
obj.page_title.includes(search_term) ||
obj.page_description.includes(search_term)
)
console.log(foundObject)
返回所需的输出。
如果要使用普通的for循环进行操作:
let foundObject=null;
for(let i=0; i < page_json.length; i++){
const exists = page_json[i].page_title === search_term || page_json[i].page_description === search_term;
if(exists) {
foundObject = page_json[i]; // What you want.
}
}
if(foundObject) { // Do something.. }
让我知道是否不清楚!
答案 1 :(得分:1)
您无需在此处使用Jquery。 Javascript具有过滤器功能,非常适合这种情况。
var search_term = "dog";
var search_results = [];
var page_json = [{
"page_title": "Display",
"page_url": "/display/",
"page_description": "We display stuff. search this description for the word dog.",
},
{
"page_title": "DRAM",
"page_url": "/dram/",
"page_description": "stuff about dram here",
},
{
"page_title": "TVs",
"page_url": "/tv/",
"page_description": "stuff about tvs here",
},
];
search = function(search_term, json) {
return json.filter(function(i) {
if (i.page_description.indexOf('about') !== -1) return i;
})
}
search_results = search(search_term, page_json);
console.log(search_results);
答案 2 :(得分:0)
要搜索正确的page_title,请输入以下内容:
<?php
if (function_exists('databaseSELECTOperation')) {
echo "function found.<br />\n";
} else {
echo "function not found<br />\n";
}
?>
或
if(page_json[i]["page_title"] == 'whatever title' && page_json[i]["page_description"] == 'whatever description'){
//do something here
}