在JavaScript中迭代经过过滤的对象属性集的最佳方式是什么

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

本文关键字:属性 最佳 方式 是什么 对象 迭代 经过 过滤 JavaScript      更新时间:2023-09-26

我得写很多

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

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

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

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

使用您所在地区的示例:

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

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

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

另一种方法是用"checked"属性/字段标记对象本身。但是,我的猜测是,你不想用像目前是否检查过这样短暂的东西污染你的物体。