首页 > 解决方案 > 在对象或数组中查找字符串的路径

问题描述

给定一个对象或数组,我希望能够确定路径是否存在。

给定 - 示例 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))

标签: javascriptrecursion

解决方案


您可以提前进行一些检查并检查 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


推荐阅读