搜索功能
var myFileArray = [
array1.items,
desportoNews.items,
array2.items,
array3.items,
array4.items
][0]
function search(searched) {
myFileArray.forEach(function() {
var results = { items: [] }
if (myFileArray.includes(searched)) {
results.items.push(myFileArray.title)
}
})
}
/搜索端点
app.get('/search', function(req, res) {
searched = 'searchword'
search(searched)
})
JSON 文件
{
"items": [
{
"title": "search on this bla bla "
}
{
"title": "search on this ble ble "
}
{
"title": "diferrent search "
}
]
}
这没有返回它应该返回的结果。端点未加载。我想在他用搜索字符串推送所有标题后输出结果数组。
最佳答案
我认为您有两个主要问题。一是您的端点未设置响应对象。您应该添加:
app.get('/search', function (req, res) {
searched="searchword";
res.json(search(searched));
});
它将以您的搜索的 json 表示形式进行响应。
此外,搜索算法正在更新结果
,其范围仅限于 forEach block ,并且不会返回或更新该闭包中的另一个变量。您需要更新搜索功能以实际返回搜索结果,然后您的端点应按预期运行。我对你的项目结构有点困惑,但这样的东西应该有效:
function search(collection, searchKeyword) {
return collection.filter(function(item) {
return item.title.includes(searchKeyword.toLowerCase());
});
}
您可以像这样调用搜索方法来获取结果:
var searchResults = search(myFileArray, 'search');
关于javascript - 用于在 JSON 文件内搜索的 Node.js 端点未返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59291344/