Given a specific object or array structure, I am looking to verify the existence of a certain path within it.
Example 1:
const path = "data/message";
const info = {
data: {
school: 'yaba',
age: 'tolu',
message: 'true'
},
time: 'UTC',
class: 'Finals'
}
If body.data.message exists in the path, the function should return true; otherwise, it should return false.
Example 2:
const path = "data/message/details/lastGreeting";
const info = {
data: {
school: 'yaba',
age: 'tolu',
message: {
content: 'now',
details: {
lastGreeting: true
}
}
},
time: 'UTC',
class: 'Finals'
}
If body.data.message.details.lastGreeting can be located in the given path, the function should return true; otherwise, it should return false.
In cases where the body contains an array:
Example 3:
const path = "data/area/NY";
const info = {
data: {
school: 'yaba',
age: 'tolu',
names : ['darious'],
area: [{
NY: true,
BG: true
}],
message: {
content: 'now',
details: {
lastGreeting: true
}
}
},
time: 'UTC',
class: 'Finals'
}
If body.data.area[0].NY is present as indicated by the path, the function should return true; otherwise, it should return false.
Here is the solution that has been devised:
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(info, path, 3))