Reputation: 1572
how can I shorten for...of syntax using arrow functions?
this.id = 1;
let products: Product[] = [
{
"id": 1,
"name": "Bycicle"
},
{
"id": 2,
"name": "iPhoneX"
}
];
for (let p of products) {
if (p.id == this.id) {
this.product = p;
break;
}
}
Can last block be written in one-liner? I tried this but it looks so wrong:
this.product = products.filter(p => p.id == this.id)[0];
I'm looking for something like .FirstOrDefault in .NET
Upvotes: 0
Views: 134
Reputation: 222682
find
should do
this.product = products.find(p => p.id === this.id);
DEMO
let id =1;
var products = [
{
"id": 1,
"name": "Bycicle"
},
{
"id": 2,
"name": "iPhoneX"
}
];
let product = products.find(p => p.id === id);
console.log(product);
Upvotes: 1
Reputation: 73251
Use Array#find
this.product = products.find(p => p.id === this.id)
To get a equivalent to firstOrDefault
, you could short circuit the result
this.product = products.find(p => p.id === this.id) || {}
Upvotes: 1