我的视图中显示了一个嵌套对象,我想从这样的查询中搜索它:
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": [{}]
}
}
我知道如何获取查询中的内容以及用户的输入内容,但是我不知道如何从已显示的内容中进行搜索和显示。
答案 0 :(得分:1)
如果您已经有了查询字符串,则可以用“ /”字符将其分隔。使用名字来查找您的第一项,使用名字来查找第二项,依此类推。
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
您仍然必须添加代码来处理以下情况,例如在当前项目中没有要查找的名称,或者有多个具有正确名称的条目,等等。为了清楚起见,我只是保持简单。