我有一个这样的嵌套对象:
let obj = {
_id: {},
person: {
$search: {
lname: true
},
_id: {},
fname: {},
something:{
$search: {
fname: true
},
}
},
code: {},
$search: {
mname: true
},
vnvEmpName: {}
}
我必须检索$search键中的所有键,即使对象包含多次出现的$search它也应该返回其中的所有键,即:
lname
fname
mname
我试过这个:
function search(obj, id) {
var result = "";
// iterate the object using for..in
for (var keys in obj) {
// check if the object has any property by that name
if (obj.hasOwnProperty(keys) && typeof obj[keys] === 'object') {
// if the key is not undefined get it's value
if (obj[keys][id] !== undefined) {
result = (obj[keys][id])
} else {
// else again call the same function using the new obj value
console.log("reahced")
search(obj[keys], id)
}
}
}
return result;
}
console.log(search(obj, '$search'))
但我只得到$search的第一个实例下的密钥( lname ) 。请帮我迭代它直到最后。