简体   繁体   English

如果属性匹配,则返回数组中的对象

[英]Return Object in Array if Property Match

Here is the scenario: 这是场景:

  • There is a parameter titled listOfSelectedProductIds that contains all of the selected ids. 有一个名为listOfSelectedProductIds的参数,其中包含所有选定的ID。

  • There is another list titled listOfAllPossibleProducts , which 还有一个名为listOfAllPossibleProducts列表,其中
    contains a list of objects . 包含objects列表。 That object contains a ProductId , object包含一个ProductId
    ProductName , and ProductCode . ProductNameProductCode It looks something like this: 看起来像这样:

在此处输入图片说明

The task at hand: 手头的任务:

  • I need to loop through my listOfSelectedProductIds . 我需要遍历listOfSelectedProductIds If the ProductId matches a ProductId from listOfAllPossibleProducts , then I need to return that object. 如果ProductId一个相匹配ProductIdlistOfAllPossibleProducts ,然后我需要返回该对象。

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. 我的循环正在按预期方式获取选定的ID,即currentItem ,但_.contains(...)始终返回false。

Question: 题:

  • What is the best way to find the objects in listOfAllPossibleProducts that have ProductIds that match my ProductIds in the listOfSelectedProductIds 什么是找到对象的最佳方式listOfAllPossibleProductsProductIds符合我的那ProductIdslistOfSelectedProductIds

How about using _.filter : 如何使用_.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! 一次创建另一个结构productsByProductId

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 并使用它来将ID映射到节点

var selectedProducts = listOfSelectedProductIds.map(getProductById)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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