如何遍历Record< K,T> [英] How to loop though Record<K, T>
本文介绍了如何遍历Record< K,T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我具有记录的 Records
类型:
export interface List {
name: string;
title: string;
}
export type RecordType
= 'recordOne'
| 'recordTwo'
| 'recordThree';
export const Records: Record<RecordType, List> = {
recordOne: {
name: 'Name1',
title: 'Ausi bere ut erit adeo enim an suae'
},
recordTwo: {
name: 'Name2',
title: 'Petebat proprie suo methodo'
},
recordThree: {
name: 'Name3',
title: 'Petebat proprie suo methodo inscitiae'
}
}
我想搜索带有特定文本的记录,但是要做到这一点,我需要遍历 Records
,那么您将如何做呢?我的意思是您会如何循环想到 Records
?
I want to search for record with specific text but in order to do that I need to loop through the Records
so how would you do that? I mean how would you loop thought the Records
?
基本上就是我想要的:
findMatchingTitle(myString) {
let title = '';
this.Records.foreach(x => {
if(myString.includes(x.title)) {
title = x.title;
}
});
return title;
}
有什么想法吗?
推荐答案
与TS并不真正相关,为了搜索标题,我首先将记录值作为数组,然后使用Array.find查找标题.
Not really related to TS, in order to search for the title, I would first get the records values as array, and use the Array.find to look for the title.
如果找到一个,我将获得它的标题
if I found one, I will get its title
const records = {
recordOne: {
name: 'Name1',
title: 'Ausi bere ut erit adeo enim an suae'
},
recordTwo: {
name: 'Name2',
title: 'Petebat proprie suo methodo'
},
recordThree: {
name: 'Name3',
title: 'Petebat proprie suo methodo inscitiae'
}
}
const findMatchingTitle = str => Object.values(records).find(record => record.title.includes(str))?.title
console.log(findMatchingTitle("inscitiae"))
这篇关于如何遍历Record< K,T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文