Here is the scenario:
There is a parameter titled listOfSelectedProductIds
that contains all of the selected ids.
There is another list titled listOfAllPossibleProducts
, which
contains a list of objects
. That object
contains a ProductId
,
ProductName
, and ProductCode
. It looks something like this:
The task at hand:
listOfSelectedProductIds
. If the ProductId
matches a ProductId
from listOfAllPossibleProducts
, then I need to return that object. Here is what I am doing:
function SelectedProducts(listOfSelectedProductIds){
for (var index = 0; index < listOfSelectedProductIds.length; index++) {
var currentItem = listOfSelectedProductIds[index];
var desiredProduct = _.contains(listOfAllPossibleProducts, currentItem);
if (desiredProduct === true) {
return listOfAllPossibleProducts[index];
}
}
}
What's currently happening:
currentItem
, but _.contains(...)
always returns false. Question:
listOfAllPossibleProducts
that have ProductIds
that match my ProductIds
in the listOfSelectedProductIds
How about using _.filter
:
var result = _.filter(listOfAllPossibleProducts, function (el) {
return _.contains(listOfSelectedProductIds, el.id);
});
Or the non-underscore method:
var result = listOfAllPossibleProducts.filter(function (el) {
return listOfSelectedProductIds.indexOf(el.id) > -1;
});
create another structure productsByProductId
once!
var productsByProductId = {};
listOfAllPossibleProducts.forEach(p => {
productsByProductId[p.ProductId()] = p
});
and maybe a helper function
function getProductById(id){
return productsByProductId[id];
}
and use this to map the ids to the nodes
var selectedProducts = listOfSelectedProductIds.map(getProductById)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.