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

Handlebars路径使用@key:筛选符合条件的method问题

筛选符合条件的method项

数据结构

{ 
  method: ['twitter','reddit','google'],
  auth: {
    twitter: {id: 213},
    reddit: {},
  }
}

需求

需要筛选出两类method:

  • 不在auth对象中的项
  • 在auth对象中但未定义id的项

预期输出:

  • 带id的auth项:twitter
  • 符合筛选条件的项:reddit、google

现有代码问题

当前代码第二部分只能识别不在auth里的google,无法识别auth中无id的reddit:

methods in auth with id:

{{#each auth}}
   {{#if id}}
      {{@key}}
   {{/if}}
{{/each}}

methods not in auth with id:

{{#each method}}
   {{#unless (lookup ../auth this)}}
      {{this}}
   {{/unless}}
{{/each}}

修复方案

修改第二部分的判断逻辑,同时检查“条目不存在”或“条目存在但无id”两个条件:

methods not in auth with id:

{{#each method}}
  {{#or (not (lookup ../auth this)) (not (lookup ../auth this).id)}}
    {{this}}
  {{/or}}
{{/each}}

如果想要更清晰的变量复用,可以用let助手暂存auth条目:

{{#each method}}
  {{#let authEntry=(lookup ../auth this)}}
    {{#or (not authEntry) (not authEntry.id)}}
      {{this}}
    {{/or}}
  {{/let}}
{{/each}}

逻辑说明:

  1. lookup ../auth this 获取当前method对应的auth对象条目
  2. (not authEntry) 判断该条目是否不存在(对应google的情况)
  3. (not authEntry.id) 判断条目存在但没有id属性(对应reddit的情况)
  4. or助手只要满足其中一个条件,就输出当前method

内容的提问来源于stack exchange,提问作者stackers

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 15:15:32