【发布时间】:2021-07-25 05:42:08
【问题描述】:
给定一个对象或数组,我希望能够确定路径是否存在。
给定 - 示例 1
const spath = "data/message";
const body = {
data: {
school: 'yaba',
age: 'tolu',
message: 'true'
},
time: 'UTC',
class: 'Finals'
}
它应该返回 true,因为消息可以在 body.data.message 中找到,否则返回 false。
给定 - 示例 2
const spath = "data/message/details/lastGreeting";
const body = {
data: {
school: 'yaba',
age: 'tolu',
message: {
content: 'now',
details: {
lastGreeting: true
}
}
},
time: 'UTC',
class: 'Finals'
}
它应该返回 true,因为 lastGreeting 可以在 body.data.message.details.lastGreeting 中找到,否则返回 false。
另一种情况是当body由一个数组组成时
给定 - 示例 3
const spath = "data/area/NY";
const body = {
data: {
school: 'yaba',
age: 'tolu',
names : ['darious'],
area: [{
NY: true,
BG: true
]]
message: {
content: 'now',
details: {
lastGreeting: true
}
}
},
time: 'UTC',
class: 'Finals'
}
它应该返回 true,因为 NY 可以在 body.data.area[0].NY 中找到,否则返回 false。
这是我想出的解决方案
const findPathInObject = (data, path, n) => {
console.log('entered')
console.log(data, path)
if(!data){
return false
}
let spath = path.split('/');
for(let i = 0; i<n; i++){
let lastIndex = spath.length - 1;
if(spath[i] in data && spath[i] === spath[lastIndex]){
return true
}
const currentIndex = spath[i];
// spath.splice(currentIndex, 1);
return findPathInObject(data[spath[currentIndex]], spath[i+1], spath.length)
}
return false
}
console.log(findPathInObject(body, spath, 3))
【问题讨论】:
-
你面临什么问题?
-
由于 spath[i+1] 而改变了 lastIndex - 我想防止这种情况发生。 lastindex 应该始终是路径中的最后一项。还要为其中包含数组的对象做出规定
-
你想要递归解决方案吗?
-
是的,递归解决方案也可以工作
标签: javascript recursion