繁体   English   中英

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

但是当我尝试使用它时,我意识到它实际上使所有内容都变得不那么紧凑和易读,当然我必须处理一个新的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。

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

另一种方法是使用“已检查”属性/字段标记对象本身。 但是,我的猜测是,您不希望通过瞬时性的方式污染对象,例如是否当前对其进行检查。

暂无
暂无

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

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