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

时间:2016-02-25 14:57:15

标签: javascript knockout.js underscore.js

以下是该方案:

  • 标题为listOfSelectedProductIds的参数包含 所有选定的ID。

  • 还有另一个标题为listOfAllPossibleProducts的清单,其中有 包含objects的列表。 object包含ProductId
    ProductNameProductCode。它看起来像这样:

enter image description here

手头的任务:

  • 我需要遍历listOfSelectedProductIds。如果ProductIdProductId中的listOfAllPossibleProducts匹配,那么我需要返回该对象。

以下是我正在做的事情:

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];
        }
    }
}

目前正在发生什么:

  • 我的循环按预期获得所选的ID,即currentItem,但是_.contains(...) 总是返回false。

问题:

  • 查找对象的最佳方法是什么? listOfAllPossibleProducts ProductIds符合我的ProductIds listOfSelectedProductIds
  • 中的pivotSheet.Activate(); Microsoft.Office.Interop.Excel.PivotTables pivotTables = (Microsoft.Office.Interop.Excel.PivotTables)pivotSheet.PivotTables(missing); int pivotTablesCount = pivotTables.Count;

2 个答案:

答案 0 :(得分:4)

如何使用_.filter

var result = _.filter(listOfAllPossibleProducts, function (el) {
  return _.contains(listOfSelectedProductIds, el.id);
});

或非下划线方法:

var result = listOfAllPossibleProducts.filter(function (el) {
  return listOfSelectedProductIds.indexOf(el.id) > -1;
});

DEMO

答案 1 :(得分:1)

创建另一个结构productsByProductId 一次!

var productsByProductId = {};
listOfAllPossibleProducts.forEach(p => {
    productsByProductId[p.ProductId()] = p
});

也许是辅助功能

function getProductById(id){
    return productsByProductId[id];
}

并使用它将id映射到节点

var selectedProducts = listOfSelectedProductIds.map(getProductById)