你如何编写上面的代码来实现我的预期结果,请帮我给出一些指针
let apis = {
home: {
index: {
url: '/index',
auth: false
},
tab: {
url: '/tab',
auth: true
}
},
test: {
test: {
url: '/test',
auth: false
}
}
}
let getItem = function (obj){
for(let item in obj){
if(obj.url === '/test') return
if(obj[item] instanceof Object)
getItem(obj[item])
}
return obj
}
console.log(getItem(apis))
预期结果:
{
url: '/test',
auth: false
}
我现在正在做这件事,但它不能达到预期的效果
:(思考
const apis = {
home: {
index: {
url: '/index',
auth: false
},
tab: {
url: '/tab',
auth: true
}
},
test: {
test: {
url: '/test',
auth: false
}
}
}
const getItem = (obj) => {
if (obj.url === '/test') {
return obj
}
for (let item in obj) {
if (obj[item] instanceof Object) {
const result = getItem(obj[item])
if (result.url === '/test') {
return result
}
}
}
return {};
}
console.log(getItem(apis))