[英]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.