【问题标题】:JSON return only the matching recordJSON 只返回匹配的记录
【发布时间】:2021-07-06 10:13:34
【问题描述】:

我正在尝试将 JSON 对象返回给 Postman,但不给它一个“标题”,例如:

{
    "name": {
        "name": "Three Rivers Campground",
        "lengthLimit": 25,
        "elevation": 6332,
        "numberOfSites": 12,
        "padType": "dirt"
    }
}

我想去掉第一个“name”,只返回name、lengthLimit、elevation、numberOfSites 和padType。到目前为止,这是我的方法代码:

app.get('/search', (req, res) => {
    let searchTerm = req.query.q;
    console.log(`Search for ${searchTerm}`);
    for(var i = 0; i<campgrounds.length; i++){
        console.log('Testing 4')
        console.log(campgrounds[i].name)
         if (searchTerm == campgrounds[i].name){
             
             return res.json({name: campgrounds[i]});
         }
        }
    return console.long('Not found');
})

我需要帮助的是:

return res.json({name: campgrounds[i]});

任何帮助将不胜感激!

【问题讨论】:

  • 代码可以优化,但您正在寻找return res.json(campgrounds[i]);
  • @LawrenceCherone 非常感谢!这有效

标签: javascript node.js json server


【解决方案1】:

如果在 campgrounds 中可能有多个匹配的 namesearch string,那么您可能需要返回一个类似的列表下面。

app.get('/search', (req, res) => {
    let searchTerm = req.query.q;
    cons result = campgrounds.filter(item => item.name === searchTerm);
    res.json(result);
    if (!result.length) {
      console.long('Not found');
    }
});

【讨论】:

    【解决方案2】:

    Lawrence Cherone 回答了我正在寻找的那一行:“return res.json(campgrounds[i]);”

    【讨论】:

      猜你喜欢
      • 2010-09-18
      • 2012-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-21
      • 2021-09-26
      • 2011-09-12
      • 1970-01-01
      相关资源
      最近更新 更多