使用lodash.find查找对象集合时返回undefined的TypeScript问题
解决lodash.find返回undefined的问题
嘿,我看了你的代码,很快就找到问题所在啦,咱们一步步来捋:
1. 最核心的问题:目标对象根本不在数组里
你设置了this.toFilterId = 2,但你的this.values数组里只push了一个id=-1的valueModel实例,数组里完全没有id=2的对象,那lodash.find肯定返回undefined呀!
2. 正确的使用示例
我给你补全了代码,添加了目标项,再调用lodash.find就能正常找到结果了:
import _ from 'lodash'; // 你的原有代码 this.toFilterId = 2; this.values = []; export class valueModel { constructor( public id: number, public code: string, public description: string ) { } } // 先往数组里添加包含目标id的项 this.values.push(new valueModel(-1, 'TestAll', 'TestAll...')); this.values.push(new valueModel(2, 'TestCode2', 'This is item with id 2')); // 调用lodash.find查找 const targetItem = _.find(this.values, (item) => item.id === this.toFilterId); console.log(targetItem); // 这里会输出id为2的valueModel实例
3. 额外要留意的细节
- 确认你已经正确安装并导入了lodash:先执行
npm install lodash,然后在文件顶部加上import _ from 'lodash'; - 如果你的数组是异步加载的(比如从接口获取),一定要等数组填充完成后再调用
find方法,不然数组还是空的,也会返回undefined - TypeScript里可以加泛型让类型更严谨:
_.find<valueModel>(this.values, item => item.id === this.toFilterId)
内容的提问来源于stack exchange,提问作者S2S2
相关产品推荐
相关产品推荐

