简体   繁体   English

对Json数据进行2级或以上深度的Javascript过滤

[英]Javascript Filter on Json Data which is 2 or more levels deep

I am working on an API in Express that filters a JSON file which contains events using the query string sent by the route. 我正在Express中使用API​​,该API使用路由发送的查询字符串过滤包含事件的JSON文件。

My JSON file has the below structure 我的JSON文件具有以下结构

{ "events": [
   {
     "venue": {
          "name": "Name of Venue",
          "address": "Address of Venue
              }
    }]
 }

I want to place the name of venue in the QueryString and filter the object, so something like this 我想将场所名称放置在QueryString中并过滤该对象,所以像这样

app.get('/api/events', function(req, res){
  var response = [];
  const { venue=null } = req.query;
  console.log(req.query);


 if (venue) {
  eventdata.filter((event) => {
   if(event.venue.name === venue){
    response.push(event);
  }
 });
}

// in case no filtering has been applied, respond with all venues
  if(Object.keys(req.query).length === 0){
    response = eventdata;
  }

  res.json(response);
});

But I think because the venue name is 2 layers deep into the object it is not creating a match. 但是我认为,由于场地名称位于对象的两层深处,因此不会创建匹配项。 I get an error 我得到一个错误

Cannot read property 'name' of undefined

If I don't put in a query string I get all the results. 如果不输入查询字符串,则会得到所有结果。

If I use localhost:3000/api/events?venue=abc%20bar I get the error. 如果我使用localhost:3000 / api / events?venue = abc%20bar,则会收到错误消息。

I'm guessing it is something to do with the depth of the "name" key/value pair in the JSON but I'm not sure. 我猜想这与JSON中“名称”键/值对的深度有关,但我不确定。 ie line 即线

if(event.venue.name === venue)

Any ideas? 有任何想法吗? Thanks 谢谢

U can do something like this: 你可以做这样的事情:

  **if(event.venue && event.venue.name) {

    }**

You can do a nested check so that you do not encounter the error( cannot read name of undefined) 您可以执行嵌套检查,以免遇到错误(无法读取未定义的名称)

That's not how filter works. 那不是filter工作原理。 The function inside should return a boolean which indicates whether the element should be kept. 内部的函数应返回一个布尔值,该布尔值指示是否应保留该元素。

So something like 所以像

var response = eventdata.filter((evt) => {
    return evt.venue && evt.venue.name && evt.venue.name == venue;
});

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

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