Javascript - 对对象执行深度搜索

标签 javascript reactjs lodash

我正在使用 .js 和 lodash

我需要能够在对象中执行深度搜索(深度和键可能会有所不同)。 例如:

这是我执行搜索所需的数据集:

const data = [
  object1: {
    key1: {
      level1: {
        filter: "this is a value"
      },
      junk: "..."
    },
    key2: {
      level1:{
        filter: ".."
      }
      junk: "this is complicated"
    },
    ...
  },
  object2: { ... },
  object3: { ... }
]

这是我的搜索条件,其中包括数据集中对象的一些属性,如果该值为 true,我将使用它作为过滤器来过滤数据

const searchCriteria = {
  key1: {
    level1: {
      filter: true,
      someOherFilter: false
    }
  },
  key2: {
    junk: true
  },
  ...
}     

因此,正如您所见,我不能依赖键的名称,我只需从搜索条件中检索所有“真实”值,将它们用作链式过滤器并搜索数据集,当它们匹配时我返回整个对象。

我可以使用以下方法从 searchCriteria 中找到真实值: const selectedFilters = _.keys(_.pickBy(filter, _.identity)) 只需将过滤器应用于对象

现在我剩下一个包含过滤器的数组: [过滤器]或[垃圾]

我们正在使用 lodash,我玩了很多 plucks、 map 、过滤器和发现..但无法得到我需要的东西。

假设我的搜索条件为:["key1", "level1", "filter] 或者我可能会将其视为 ["key2", "junk"]

编写深度搜索功能的最佳方法是什么,最好使用 lodash?

最佳答案

没有lodash的解决方案:

此处 getKeyByPathArr 获取 2 个参数:对象和关键级别的数组,并返回一个null 如果键不存在或参数错误。

// @param o <object>
// @param pathArr <array> of key levels
// @return o[key] value where key = pathArr.join(.) and value exists, 
// otherwise return null. If pathArr === [] return o

const getKeyByPathArr = o => pathArr => (Array.isArray(pathArr)) 
    ? pathArr.reduce((a, c) => (a[c] != null) ? a[c] : null, o)
    : null;
    
const data = {
  object1: {
    key1: { level1: { filter: "this is a value" } },
    key2: { junk: "this is complicated" },
  },
  object2: {},
  object3: {}
};

const keys1 = ["key1", "level1", "filter"];
const keys2 = ["key2", "junk"];

const result1 = getKeyByPathArr(data.object1)(keys1);
const result2 = getKeyByPathArr(data.object1)(keys2);

console.log(result1)
console.log(result2)

关于Javascript - 对对象执行深度搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44062691/

相关文章:

javascript - 如何在 jScrollPane 中获取最大滚动高度?

css - 如何使其父 div 的 NextJS Image 组件的高度和宽度为 100%?

javascript - 模板内的 Lodash 调用函数

javascript - 重构 Lodash 代码

javascript - 按值对映射/哈希进行排序,保留键

javascript - 如何在 Javascript 对象中动态引用变量键名称?

JavaScript 对象设计

javascript - 允许替换特定文本

reactjs - 使用react-pdf react 嵌入PDF不起作用

javascript - ReactJS:有更好的方法吗?