What is the best way to access a specific object based on a property from an API response? In my scenario, I have an array of Products retrieved properly from my server. The watchedProducts
class has a property called productId
which corresponds to the id
in the Product
object. My question is, how can I efficiently iterate over these arrays to retrieve the products
where
watchedProduct.productId == product.id
?
Code:
export class MyProductsComponent implements OnInit {
watchedProducts: WatchedProduct[] = [];
products: Product[] = [];
constructor(private dataService: DataService) {}
ngOnInit() {
this.getWatchedProducts();
}
getWatchedProducts(): void {
this.dataService.getObjects(WatchedProduct).subscribe(result => {
this.watchedProducts = result.object;
//get watched product, its work fine
});
this.dataService.getObjects(Product).subscribe(result => {
this.products = ...
//what to do next?
//i want to get that products, where watchedProducts[i].productId == products[i].id
});
}
}
EDIT
I have a SQL Server where the table Products
is related to WatchedProducts
like parent-child. ProductId
in WatchedProducts is FK for Id
in Products
products
looks like this:
https://i.sstatic.net/W5QSm.png
And watchedProducts
:
https://i.sstatic.net/mGME1.png
In this scenario,
Product.id == 8 === WatchedProduct.ProductId == 8
My question is, how to get products
array where
watchedProduct.productId == product.Id
?
EDIT2
Based on one answer, I did the following:
getWatchedProducts(): void {
this.dataService.getObjects(WatchedProduct).subscribe(result => {
this.errorService.showError(result);
this.watched = result.object;
});
this.dataService.getObjects(Product).subscribe(result => {
this.errorService.showError(result);
this.products = result.object;
for (let i = 0; i < this.watched.length; i++) {
for (let j = 0; j < this.products.length; j++) {
if (this.watched[i].productId == this.products[j].id)
this.watchedProducts.push(this.products[j]);
}
}
});
}
Sometimes I need to refresh the browser multiple times to get a response with product objects. Could you help me identify what I am doing wrong here?