简体   繁体   中英

Return Object in Array if Property Match

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:

  • I need to loop through my 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:

  • My loop is getting the selected id as expected ie currentItem , but _.contains(...) always returns false.

Question:

  • What is the best way to find the objects in 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;
});

DEMO

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM