繁体   English   中英

如果正在搜索值,如何在数组中返回 json 对象

[英]How can I return a json object in an array if the value is being searched for

这是我第一次尝试将 HTTPS 请求实现到代码中,所以我不是 100% 有信心使用它。 所以我的目标是用 JSON 对象在我的数组中搜索一个术语并返回与该值相关的所有内容。 这是我的代码:

const campgrounds = [{
    name: "Three Rivers Petroglyph Site",
    town: "Lincoln, NM",
    lengthLimit: 25,
    elevation: 4986,
    numberOfSites: 7,
    padType: "gravel"
  },
  {
    name: "Baca Campground",
    town: "Lincoln, NM",
    lengthLimit: 32,
    elevation: 6397,
    numberOfSites: 7,
    padType: "dirt"
  },
  {
    name: "South Fork Campground",
    town: "Nogal, NM",
    lengthLimit: 19,
    elevation: 7513,
    numberOfSites: 60,
    padType: "unknown"
  }
]

app.get('/search', (req, res) => {
  let searchTerm = req.query.q;
  console.log(`Search for ${searchTerm}`);

  for (const campground of campgrounds) {
    if (campground == campgrounds.name) {
      res.json({
        campgrounds: campground
      });
    }
  }
});

避免在循环内调用res.json 改为生成结果(数组),然后在最后调用res.json - 在循环之外。

像这样的东西

...

app.get('/search', (req, res) => {
  let searchTerm = req.query.q;
  console.log(`Search for ${searchTerm}`);

  const results = []

  for (const campground of campgrounds) {
    if (campground.name == searchTerm) {
      results.push(campground);
    }
  }
  res.json({
     campgrounds: results
  })
});

我想出了这对我有用的东西,并通过 Postman 运行它并通过了我的测试

app.get('/search', (req, res) => {
    let searchTerm = req.query.q;
    console.log(`Search for ${searchTerm}`);

    // TODO

        for (const campground of campgrounds) {
                if (campground.name == searchTerm){
                        res.json(campground);
                }
        }
});

以下是我通过 Postman 运行的测试:

pm.test("name check", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.name).to.eql('Three Rivers Campground');
});
pm.test("length check", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.lengthLimit).to.eql(25);
});
pm.test("elevation check", function () {
    var jsonData = pm.response.json();
    pm.expect(jsonData.elevation).to.eql(6332);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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