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

如何通过Lodash get()方法获取取反后的值?

解决lodash get()取反返回值的需求

lodash的get()方法本身不支持在路径参数中通过!前缀直接返回取反后的值,不过可以通过以下几种方式实现你的需求:

1. 封装自定义的带取反逻辑的get工具函数

这是最贴合你需求的方案,自己封装一个工具函数,处理路径中的!前缀,内部调用lodash.get后返回取反或原值:

import _ from 'lodash';

// 自定义带取反支持的get函数
export function getWithNegation(obj, path, defaultValue) {
  let shouldNegate = false;
  // 处理字符串路径
  if (typeof path === 'string' && path.startsWith('!')) {
    shouldNegate = true;
    path = path.slice(1);
  }
  // 可选:处理数组形式的路径(比如['!styling', 'fullWidth'])
  else if (Array.isArray(path) && path[0]?.startsWith('!')) {
    shouldNegate = true;
    path = [...path];
    path[0] = path[0].slice(1);
  }
  
  const originalValue = _.get(obj, path, defaultValue);
  return shouldNegate ? !originalValue : originalValue;
}

在Vue项目里,你可以把这个函数注册为全局方法,方便所有组件调用:

// 在main.js中
import Vue from 'vue';
import { getWithNegation } from '@/utils/your-tool-file';

Vue.prototype.$getWithNegation = getWithNegation;

之后在组件里就能像你预期的那样使用:

// 获取取反后的值
const isNotFullWidth = this.$getWithNegation(someObject, '!styling.fullWidth');
// 正常获取值
const isFullWidth = this.$getWithNegation(someObject, 'styling.fullWidth');

2. 函数式组合(适合零散场景)

如果只是偶尔使用,不想封装函数,可以直接链式调用实现取反:

import _ from 'lodash';

// 直接取反
const isNotFullWidth = !_.get(someObject, 'styling.fullWidth');
// 或者用flow实现函数式组合
const getAndNegate = _.flow([
  path => _.get(someObject, path),
  val => !val
]);
const isNotFullWidth = getAndNegate('styling.fullWidth');

注意事项

  • 取反逻辑遵循JavaScript的真值假值规则:0、''、null、undefined、false、NaN这些值取反后都会得到true,确保这符合你的业务预期。
  • 如果你的路径是数组形式(比如['styling', 'fullWidth']),自定义函数里的数组路径处理逻辑可以按需启用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:10:34