在 JavaScript 中遍历对象的过滤属性集的最佳方法是什么?

What is the best way to iterate through a filtered set of properties of an object in JavaScript?

我不得不写很多

for ( var prop in obj ) 
{
   if ( condition(prop) ) 
   {
      // ... 
   }
}

-我的生产代码中的类型部分。以下是直接复制粘贴的几个例子

(1)

    for ( var region in this.DealsByRegion ) // iterate through regions
    {
        if ( this.RegionsChecked[region] === true ) // if region is checked in table   
        {
            num_deal_opportunities += region.NumOpportunities;
            total_deal_percentage += region[dealName] * region.NumOpportunities;
        }    

    }

(2)

for ( var deal_name in this.DealsChecked ) 
{
    if ( this.DealsChecked[deal_name] === true ) 
    {
        offer_data.push({ value: deal_percentages[deal_name], 
                          color: this.ColorStack[(this.ColorStack.length + i) % this.ColorStack], 
                          highlight: this.HighlightColor, 
                          label: deal_name });
    }       
}

当然还有很多

for ( var thisguy in theseguys ) 
{
   if (theseguys.hasOwnProperty(thisguy)
   {
     // ... 
   }
}

我想知道是否有办法让它更优雅、更紧凑。我尝试写一个类似 LINQ 的 Where 子句

// helper function for iterating through a filtered set of properties
Object.prototype.PropsWhere = function ( cond ) 
{
    var propsWhere = [];
    for ( var prop in this ) 
    {
        if ( cond(prop) ) 
        {
            propsWhere.push(prop);  
        }   
    }
    return propsWhere;
}

但是当我尝试使用它时,我意识到它实际上使所有内容变得 less 紧凑且可读,当然我必须处理有了新的 this 和 yada-yada。

我应该如何处理这些情况?

如果您发现必须编写大量循环访问对象属性的条件语句 - 您可能需要重新检查架构。

使用您的区域示例:

for ( var region in RegionsChecked ) // iterate through checked regions
{
    num_deal_opportunities += region.NumOpportunities;
    total_deal_percentage += region[dealName] * region.NumOpportunities;
}

通过这种方式,您的容器仅包含对您关心的对象的引用 - 而不是创建 "meta-containers" 告诉您您关心的对象的 ID。

不确定这对您的基础架构是否可行 - 但看看您是否可以创建所需对象的容器 - 而不是中间容器,它会告诉您您需要其他容器中的哪些对象。

另一种方法是用 "checked" property/field 标记对象本身。但是,我的猜测是你不想用一些短暂的东西来污染你的对象,比如它们当前是否被检查。