我有从JSON对象生成的大型菜单,如下所示:
[
{
"name":"Menu Item 1",
"id":"8",
"children":[
{
"name":"Sub Menu 1-1",
"id":"1",
"children":[
{
"name":"Sub Menu 1.1.1",
"id":"2"
},
{
"name":"Sub Menu 1.1.2",
"id":"3"
}
]
},
{
"name":"Sub Menu 1.2",
"id":"4"
}
]
},
{
"name":"Menu Item 2",
"id":"7",
"children":[
{
"name":"Sub Menu 2.1",
"id":"5"
},
{
"name":"Sub Menu 2.2",
"id":"6"
}
]
}
]
如何创建自定义过滤器,以便在不更改原始结构的情况下以递归方式检索匹配的项目?
答案 0 :(得分:1)
试试这个。
var menuItems =[{ name: 'Menu Item 1', id: '8', children:[{ name: 'Sub Menu 1-1', id: '1', children: [{ name: 'Sub Menu 1.1.1', id: '2' }, { name: 'Sub Menu 1.1.2', id: '3' }] }, { name: 'Sub Menu 1.2', id: '4' }]},{ name: 'Menu Item 2', id: '7', children: [{ name: 'Sub Menu 2.1', id: '5' }, { name: 'Sub Menu 2.2', id: '6' }] }];
var result = [];
function isObject(obj) {
return (!!obj.name && !!obj.id);
}
function hasChildren(obj) {
return !!obj.children && Array.isArray(obj.children);
}
function getNameList(item, matchName) {
if(Array.isArray(item)) {
for(var i = 0; i < item.length; i++) {
if(hasChildren(item[i])) {
getNameList(item[i].children, matchName);
}
if(isObject(item[i])) {
if(matchName == item[i].name) result.push(item[i]);
}
}
}
}
getNameList(menuItems, 'Menu Item 1');
console.log(result);