在JavaScript中迭代对象的一组过滤属性的最佳方法是什么?

时间:2015-12-23 23:29:48

标签: javascript linq javascript-objects

我不得不写很多

for ( var prop in obj ) 
{
   if ( condition(prop) ) 
   {
      // ... 
   }
}
我的生产代码中的

-type部分。以下是直接复制粘贴的几个示例。

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

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

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

1 个答案:

答案 0 :(得分:1)

如果您发现自己必须编写大量迭代对象属性的条件语句,则可能需要重新检查模式。

使用您的区域示例:

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

通过这种方式,您的容器只包含对您关注的对象的引用 - 而不是创建"元容器"告诉你你关心的对象的id。

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

另一种方法是使用"标记"标记对象本身。属性/字段。但是,我的猜测是,你不想用一些短暂的东西来污染你的物品,无论它们当前是否被检查过。

相关问题