如何在单次JMESPath查询中执行多搜索语句(JavaScript环境)
在JavaScript中用JMESPath单次查询合并多字段数组
JMESPath不支持直接传入数组形式的查询条件,你需要用它原生的表达式语法来一次性合并多个字段的数组结果,避免循环遍历提升效率。
正确的查询表达式
有两种常用写法都能实现需求:
- 使用
flatten函数处理嵌套数组:flatten([domains[], subdomains[]]) - 直接用加法运算符合并数组(主流JMESPath实现如jmespath.js支持):
domains[] + subdomains[]
代码示例
假设你的目标对象是:
const arrayItem = { domains: ["somedomain.com", "otherdomain.com"], subdomains: ["mail", "docs"] };
使用jmespath.js库执行查询:
const jmespath = require('jmespath'); // 写法1:flatten函数 const result1 = jmespath.search(arrayItem, 'flatten([domains[], subdomains[]])'); // 写法2:加法运算符 const result2 = jmespath.search(arrayItem, 'domains[] + subdomains[]'); console.log(result1); // 输出 ["somedomain.com", "otherdomain.com", "mail", "docs"] console.log(result2); // 输出相同结果
原理说明
[domains[], subdomains[]]会先提取两个字段的数组,生成一个嵌套数组[["somedomain.com", "otherdomain.com"], ["mail", "docs"]]flatten()函数会将嵌套数组扁平化,直接得到一维结果数组- 加法运算符
+则是JMESPath提供的语法糖,直接将两个数组合并为一维数组,效果与flatten一致
内容的提问来源于stack exchange,提问作者nxtlvl
相关产品推荐
相关产品推荐

