简体   繁体   中英

Node.js endpoint to search inside JSON file not returning

Search function

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

/search Endpoint

app.get('/search', function(req, res) {
    searched = 'searchword'
    search(searched)
})

JSON File

{
  "items": [
    {
      "title": "search on this bla bla "
    }
    {
      "title": "search on this ble ble "
    }
    {
      "title": "diferrent search "
    }
  ]
}

This is not returning what it was supposed to. The endpoint doesn't load. I want to output the results array after he pushed all titles with searched string.

I think the you have two main issues. One is that your endpoint isn't setting up the response object. You should add:

app.get('/search', function (req, res) {
  searched="searchword";
  res.json(search(searched));
});

That will respond with the json representation of your search.

Additionally the search algorithm is updating results which is scoped to just the forEach block and is not returning or updating another variable in that closure. You need to update your search function to actually return the results of the search first and then your endpoint should function as expected. I'm a little confused as to your items structure, but something like this should work:

function search(collection, searchKeyword) {
    return collection.filter(function(item) { 
      return item.title.includes(searchKeyword.toLowerCase()); 
    });
}

and you can call the search method like so to get your results:

var searchResults = search(myFileArray, 'search');

runnable jsbin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM