Issue
I have a table where I store the sales of certain products. I need to fetch the records by client id.
I did like this:
public async getData(clientID: any): Promise<any> {
try {
return await client
.scan({
TableName: "dbSales",
FilterExpression: "contains(clientID, :clientID)",
ExpressionAttributeValues: {
":clientID": clientID,
},
})
.promise()
.then(async (response) => {
let data = [];
for (let i = 0; i < response.Count; i++) {
if(data.filter(product => product.productId == response.Items[i]['productId']) != undefined){
const resultData = await this.getProduct(response.Items[i]['productId']);
data.push(resultData);
}
}
return {
status: 200,
data: data,
};
})
.catch((error: AxiosError) => {
throw error;
});
} catch (e) {
throw new HttpError(500, e.message);
}
}
There it will get all the records with that customer id, and then through a condition it will get the product name of each record it found, through another function (getProduct), with the repetition loop.
The problem is that I'm getting a lot of repeated results, i.e. for the same product id and customer.
I need that when there is more than one record in dbSales with the same customer id and with the same product id, it returns me only one result for those records.
That is, one row for each record that contains the same customer ID and product ID.
This is generating a long delay in the search for data, as I only need which products a particular customer has purchased, without the information being repeated when he has more purchases of the same product.
Solution
Problem solved! Solution:
The solution presented by our friend @jarmod solved my problem, in a simple way.
let result = response.Items.filter((e, i) => {
return response.Items.findIndex((x) => {
return x.productId == e.productId}) == i;
});
for (let i = 0; i < result.length; i++) {
if(data.filter(product => product.productId == result[i]['productId']) != undefined){
const resultData = await this.getProduct(result[i]['productId']);
data.push(resultData);
}
}
Proposed solution: How to remove duplicates objects in array based on 2 properties?
Answered By - Clebson
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.