从对象获取唯一项

时间:2015-05-20 20:39:37

标签: javascript jquery

我有一个javascript对象,它是从数据库调用动态创建的,如下所示:

{
  department: 'Fraud',
  location: 'APAC'
},
{
  department: 'Disputes',
  location: 'APAC'
},
{
 department: 'Fraud',
 location: 'EMEA'   
} 

此对象由以下内容创建:

$(data).find('areas > option').each(function(){

    // Define data
    areas = $(this);

   // Define our vars
   department = $(areas).find('departmentDesc').text();
   areaDesc = $(areas).find('areaDesc').text();

   // Push items to our object
   impactedAreasArray.push({area: areaDesc, department: department});
});

我要做的是检查此对象以查看是否有超过5个项目使用以下内容:

if(impactedAreasArray.length > 5){
  // If so, I want to get all of the unique areas and store them in an array
}else{
  // If not, I want to get all of the unique departments and store them in an array
}

我打算再次循环遍历对象并将它们推送到另一个阵列,如果它们已经不存在但它似乎效率低下而且我想知道是否可以通过映射或者更优雅的解决方案

关键是如果选择了25个部门,我只想显示受影响的区域而不是列出所有25个部门。如果只有4个部门受到影响,那么它就足够短,只能向4个部门展示。

1 个答案:

答案 0 :(得分:2)

使用其属性为部门和位置名称的对象。这将自动使它们独一无二。

var locations = {};
var departments = {};
impactedAreasArray = [];

$(data).find('areas > option').each(function(){

    // Define data
    areas = $(this);

   // Define our vars
   department = $(areas).find('departmentDesc').text();
   areaDesc = $(areas).find('areaDesc').text();

   // Push items to our object
   impactedAreasArray.push({area: areaDesc, department: department});
   locations[areaDesc] = true;
   departments[department] = true;
});

如果您想将它们作为数组,则可以执行以下操作:

locations = Object.keys(locations);
departments = Object.keys(departments);