簡體   English   中英

從req.query搜索對象內部

[英]Search inside an object from the req.query

我有一個嵌套的對象顯示在我的視圖中,我想從這樣的查詢中搜索它:

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

我的對象是這樣的:

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

如果我有http://localhost:3000/test?$folder=folder那么我會:

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

如果我有http://localhost:3000/test?$folder=folder/subFolder那么我將有:

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

我知道如何獲取查詢中的內容以及用戶的輸入內容,但是我不知道如何從已經顯示的內容中進行搜索和顯示。

如果您已有查詢字符串,則可以用“ /”字符將其分隔。 使用名字來查找您的第一個項目,使用名字來查找第二個項目,依此類推。

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

您仍然必須添加代碼來處理以下情況,例如在當前項目中沒有要查找的名稱,或者具有正確名稱的多個條目,等等。 為了清楚起見,我只是保持簡單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM