I have the following 2 objects. How can I remove items from listProposalProducts
that don't have a coverageLineId
that matches an id
from coverageLinesSelectedItems
? In this example, I want to remove item 1 from listProposalProducts
because an id of 2 does not exist in coverageLinesSelectedItems
. I think I'm looking for the opposite of the pop() method but I'm not sure how to get the correct index to splice out of listProposalProducts
.
let listProposalProducts = [
0: {productId: 101391, coverageLineId: 1},
1: {productId: 101591, coverageLineId: 2},
2: {productId: 151391, coverageLineId: 3}
]
let coverageLinesSelectedItems = [
0: {id: 1, itemName: 'Medical'},
3: {id: 3, itemName: 'Vision'}
]
CodePudding user response:
You could use Array.filter
combined with Array.some
to filter the results. E.g.
let listProposalProducts = [
0: {productId: 101391, coverageLineId: 1},
1: {productId: 101591, coverageLineId: 2},
2: {productId: 151391, coverageLineId: 3}
]
let coverageLinesSelectedItems = [
0: {id: 1, itemName: 'Medical'},
3: {id: 3, itemName: 'Vision'}
]
let requiredResult = listProposalProducts.filter(
item => coverageLinesSelectedItems.some(
cov => cov.id === item.coverageLineId
)
);
This keeps only the products whose coverageLineId
matches the id
of a coverageLinesSelectedItems
element.
CodePudding user response:
A simple straight forward implementation would be:
listProposalProducts.filter((it) => coverageLinesSelectedItems.find((other) => other.id === it.coverageLineId))
If the objects are larger, you might want to compute a map from the lookup object.
const lookup = {}
coverageLinesSelectedItems.forEach((it) => {lookup[it.id] = true;})
listProposalProducts.filter((it) => lookup[it.coverageLineId])