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

使用Lodash从大型对象数组中提取含def属性的对象

解决方案:用Lodash提取包含指定属性的对象

没问题,这事儿用Lodash的工具函数就能轻松解决,核心思路是过滤数组中自身包含def属性的对象,不管该属性的取值是什么(哪怕是null、undefined或者假值都没关系)。

方法一:_.filter + _.has(推荐)

这是最精准的写法,_.has()会严格检查对象自身是否存在指定属性(不会包含继承来的属性),完全符合你的需求:

const _ = require('lodash'); // 先确保引入Lodash

// 假设你的大型数组是yourLargeArray
const filteredArray = _.filter(yourLargeArray, (obj) => _.has(obj, 'def'));

方法二:原生in运算符(可选)

如果你需要包含继承来的def属性,可以用原生的in运算符替代_.has():

const filteredArray = _.filter(yourLargeArray, (obj) => 'def' in obj);

示例验证

举个实际例子看看效果:

const yourLargeArray = [
  { id: 1, def: 'active' },
  { id: 2, name: 'no-def' },
  { id: 3, def: null },
  { id: 4, def: undefined },
  { id: 5, def: 0 }
];

const result = _.filter(yourLargeArray, (obj) => _.has(obj, 'def'));
// result会包含id为1、3、4、5的对象,因为它们都有def属性

这种写法效率也很高,Lodash的_.filter内部做了优化,处理大型数组完全没问题~

内容的提问来源于stack exchange,提问作者Leonel Matias Domingos

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:08:16