我正在尝试创建一个通过键和值递归搜索对象的函数。 我不知道如何做到这一点并尝试了不同的例子。 有人可以帮我吗?
我有这个物体:
var menuObj = {
"mainmenu": [
{
"id" : 72,
"menu_id" :1 ,
"parent_id" : 0,
"href" : "{\"routeName\":\"post-page\",\"routeParams\":{\"slug\":\"algemene-voorwaarden\"}}",
"permission" : null,
"hierarchie" : 0,
"blank" : 0,
"status" : "published",
"label" : "Algemene Voorwaarden",
"children":[]
},
{
"id" : 73,
"menu_id" : 1,
"parent_id" : 0,
"href" : "{\"routeName\":\"post-page\",\"routeParams\":{\"slug\":\"privacy\"}}",
"permission" : null,
"hierarchie" : 1,
"blank" : 0,
"status" : "published",
"label" : "Privacy",
"children" : [
{
"id" : 101,
"menu_id" : 1,
"parent_id" : 73,
"href" : "{\"routeName\":\"blog\"}",
"permission" : null,
"hierarchie" : 2,
"blank" : 0,
"status" : "published",
"label" : "blog",
"children" : [
{
"id" : 102,
"menu_id" : 1,
"parent_id" : 101,
"href" : "{\"routeName\":\"blog\",\"routeParams\":{\"category_slug\":\"categorie-2\"}}",
"permission" : null,
"hierarchie" : 3,
"blank" : 0,
"status" : "published",
"label" : "Categorie 2",
"children" : []
}
]
}
]
}
]
};
假设我需要这样的东西:
fnFindKeyValuePair(obj, key, value) {
// return true/false/null/undefined or found obj
}
搜索示例:
fnFindKeyValuePair(menuObj['mainmenu'], 'href', "{\"routeName\":\"blog\"}")
预期结果:返回
true
-ish 或:
{
"id" : 101,
"menu_id" : 1,
"parent_id" : 73,
"href" : "{\"routeName\":\"blog\"}",
"permission" : null,
"hierarchie" : 2,
"blank" : 0,
"status" : "published",
"label" : "blog",
"children" : [
{
"id" : 102,
"menu_id" : 1,
"parent_id" : 101,
"href" : "{\"routeName\":\"blog\",\"routeParams\":{\"category_slug\":\"categorie-2\"}}",
"permission" : null,
"hierarchie" : 3,
"blank" : 0,
"status" : "published",
"label" : "Categorie 2",
"children" : []
}
]
}
我是这样做的:
static find_by_id(obj, key, value ) {
if (obj[key] === value) {
return obj
}
for (const [k, v] of Object.entries(obj)) {
if(v && typeof(v) === 'object') {
let x = find_by_id(v, key, value)
if (x) {
return x
}
}
}
}