I have a custom object that is defined as following (names and properties have been simplified to avoid confidential information leakage):
type T = {
id: number;
title: string;
};
This type is used to create a list of T
s like so:
const IT: StringMap<T> = {
a: {
id: 0,
title: 'foo',
},
b: {
id: 1,
title: 'bar',
},
c: {
id: 2,
title: 'foobar',
},
}
I need a way to be able to retrieve one of these T
type objects based on their id
. So I created the following function:
const getTUsingId = (ts: StringMap<T>, id: number): T => {
Object.values(ts).forEach((t: T) => {
if (t.id === id) {
return t
}
});
// This is as a safeguard to return a default value in case an invalid id is passed
return ts['a']
}
For whatever reason, this function will always return ts['a']
regardless of what id
I pass to it. Console logging t.id === id
even returns true
but it still carries on until the end of the ts
map!
Any help is highly appreciated!
CodePudding user response:
return
won't break out of your loop. You need to use a plain for
loop:
const getTUsingId = (ts: StringMap<T>, id: number): T => {
for (const t of Object.values(ts)) {
if (t.id === id) {
return t
}
}
return ts['a']
}
CodePudding user response:
the forEach callback is for performing an action on every element in the array, it's return isn't used for termination, what you want is filter
, find
or a regular for loop
Object.values(ts).filter((t: T) => {
return t.id === id;
});
return all values where the id matches as a fresh array, you would use this if there was a possibility of multiple match, you would then need to parse the returned array to decide which match was correct
Object.values(ts).find((t: T) => {
return t.id === id;
});
return only the first matching value
for(const t of Object.values(ts))
if (t.id === id) {
return t
}
});
my preference would be find
const getTUsingId = (ts: StringMap<T>, id: number): T => {
return Object.values(ts).find((t: T) => t.id === id) ?? ts['a']
}