You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在单次JMESPath查询中执行多搜索语句(JavaScript环境)

在JavaScript中用JMESPath单次查询合并多字段数组

JMESPath不支持直接传入数组形式的查询条件,你需要用它原生的表达式语法来一次性合并多个字段的数组结果,避免循环遍历提升效率。

正确的查询表达式

有两种常用写法都能实现需求:

  1. 使用flatten函数处理嵌套数组:
    flatten([domains[], subdomains[]])
    
  2. 直接用加法运算符合并数组(主流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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 02:10:26