I frequently utilize this particular pattern in my Typescript coding:
class Vegetable {
constructor(public id: number, public name: string) {
}
}
var vegetableArray = new Array<Vegetable>();
vegetableArray.push(new Vegetable(1, "Carrot"));
vegetableArray.push(new Vegetable(2, "Bean"));
vegetableArray.push(new Vegetable(3, "Peas"));
var id = 1;
var collection = vegetableArray.filter(xVegetable => {
return xVegetable.id == id;
});
var item = collection.length < 1 ? null : collection[0];
console.info(item.name);
I am considering developing a JavaScript extension that mimics the LINQ SingleOrDefault
method to return null
if an item is not found in the array:
var item = vegetable.singleOrDefault(xVegetable => {
return xVegetable.id == id;
});
I'm wondering if there's an alternative approach to achieve this without having to create a custom interface?