I have Records type of Record:
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'
}
}
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 ?
Basically that is what I want:
findMatchingTitle(myString) {
let title = '';
this.Records.foreach(x => {
if(myString.includes(x.title)) {
title = x.title;
}
});
return title;
}
Any ideas?
For me to iterate over a Record<string, string> and needing both the key and the value, this did the trick:
const formData = new FormData();
for (const [key, value] of Object.entries(myRecord)) {
formData.append(key, value);
}
Generally to loop through Objects you can do:
for(let prop in obj) console.log(obj[prop])
However typescript wont let you do that with no implicit any, which is why you'd have to type cast:
for (let prop in Records) console.log((Records as any)[prop]);
Another way to loop through an Object and compare properties is with Object.keys and Object.values as shown below
function findMatchingTitle(myString: string): string {
for (let index in Object.keys(Records)) {
let title: string = Object.values(Records)[index].name;
if (title.includes(myString))
return title;
}
return '';
}
Alternatively, for an exact search it would be:
function findMatchingTitle(myString: string): string {
for (let index in Object.keys(Records)) {
let title: string = Object.values(Records)[index].name;
if (title === myString)
return title;
}
return '';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With