javascript - 在对象或数组中查找字符串的路径
问题描述
给定一个对象或数组,我希望能够确定路径是否存在。
给定 - 示例 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。
另一种情况是当主体由一个数组组成时
给定 - 示例 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))
解决方案
您可以提前进行一些检查并检查 path 是否是一个空字符串,然后退出true
.
通过拥有一个数组,您可以通过省略索引来使用实际路径检查数组的元素来提前退出。
对于键的最终检查,您可以检查它的存在,并返回 recursove 调用的结果false
,如果该键不在对象中,则返回其余路径或 return 。
const
findPathInObject = (data, path) => {
if (!path) return true;
if (!data || typeof data !== 'object') return false;
if (Array.isArray(data)) return data.some(d => findPathInObject(d, path));
const
spath = path.split('/'),
key = spath.shift();
return key in data
? findPathInObject(data[key], spath.join('/'))
: false;
};
console.log(findPathInObject({ data: { school: 'yaba', age: 'tolu', message: 'true' }, time: 'UTC', class: 'Finals' }, "data/message", 3)); // true
console.log(findPathInObject({ data: { school: 'yaba', age: 'tolu', message: { content: 'now', details: { lastGreeting: true } } }, time: 'UTC', class: 'Finals' }, "data/message/details/lastGreeting", 3)); // true
console.log(findPathInObject({ data: { school: 'yaba', age: 'tolu', names: ['darious'], area: [{ NY: true, BG: true }], message: { content: 'now', details: { lastGreeting: true } } }, time: 'UTC', class: 'Finals' }, "data/area/NY", 3)); // true
推荐阅读
- android - 如何在给定不同大小/纵横比的情况下使流式上传的视频保持一致
- python - 是否有用于将数据集拆分为训练、验证和测试的 python 函数?
- python - 列表中元素的映射
- rust - 如何通过宏获取已声明的变量名和变量类型
- java - 为什么Spring Data MongoDB不提供Aggregate操作的“hint”选项,mongodb Driver有,但我不知道怎么用
- regex - 提取方括号中的文本(括号内的属性之间有分隔符)
- javascript - 重新创建 Google 图片布局
- c# - 无法将 System.Datetime 转换为字符串错误
- typescript - Angular 7 绑定指令
- python - ValueError:时间数据 '12/31/2017' 与格式 '%d-%m-%Y' 不匹配