简体   繁体   中英

Search inside an object from the req.query

I have a nested object displayed in my view and i want to search in it from the query like this :

http://localhost:3000/test?$folder=folder

My object is like this :

   const test = {
        "item": [
          {
            "name": "folder",
            "item": [{
                "name": "subFolder",
                "item": [
                  {
                    "name": "subFolderTest1",
                    "item": [{
                      "path": "/",
                      "items": [{
                        "method": "GET",
                      }]
                    }]
                  },
                  {
                    "name": "subFolderTest2",
                    "item": [{
                      "path": "/",
                      "items": [{
                        "method": "GET",
                      }]
                    }]
                  }
                ]
            }]
        }
      ]
    }

If i have http://localhost:3000/test?$folder=folder then i would have :

   {
        {
            "name": "subFolder",
            "item": [{},{}]
        }
   }

And if i have http://localhost:3000/test?$folder=folder/subFolder then i will have :

{
          {
            "name": "subFolderTest1",
            "item": [{}]
          },
          {
            "name": "subFolderTest2",
            "item": [{}]
          }
    }

I know how to get what's inside my query and what the user's input but i don't how to search and display from something which is already displayed.

If you already have your query string you could split it by the "/" character. Use the first name to find your first item, the second name to find the second, and so on.

var folder = "folder/subFolder";
var path = folder.split("/");
var currentItem = test["item"];

// Get each name you are looking for
path.forEach(function(name) {
    // get each entry of the current item
    currentItem.forEach(function(entry) {
        // if the name of the entry is the same as the 
        // name you are looking for then this is the 
        // next item you are looking for
        if (entry.name == name) {
            currentItem = entry["item"];
        }
    });
});

// now currentItem should be the entry specified by your path

You will still have to add code to handle situations like not having the name you are looking for in your current item, or having multiple entries with the correct name, and so on. I just kept it simple for the sake of clarity.

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