如何筛选具有唯一属性组合的对象

时间:2017-09-03 03:20:02

标签: javascript filter javascript-objects

var place =[
 {city: "Durham, NC, United States", begin: "09/04/2017", id: 0},
 {city: "Raleigh, NC, United States", begin: "09/11/2017", id: 1},
 {city: "Durham, NC, United States", begin: "09/25/2017", id: 2},
 {city: "Durham, NC, United States", begin: "09/25/2017", id: 3}
]

从上面开始,我想创建一个包含仅具有唯一city / begin属性组合的对象的新数组。因此,就上述数组而言,结果将仅包括前3个对象,因为对象3和4包含相同的city / begin属性。

我已尝试过for / if以及其他数组方法的各种组合但没有成功,所以任何建议都会受到赞赏。

3 个答案:

答案 0 :(得分:0)

您可以在此处使用地图。 地图中的键为city,值为begin的数组。然后,您可以使用此地图过滤掉重复项。

var map = new Map;
var len = place.length;
var newArr = [];
for( i = 0; i < len; i++ ){ 
var obj = place[i];
if(map[obj.city] === undefined || map[obj.city] === null){
    map[obj.city] = [];
    map[obj.city].push(obj.begin); 
    newArr.push(obj);
}else if(!map[obj.city].includes(obj.begin)){
    map[obj.city].push(obj.begin); 
    newArr.push(obj);
}
}

答案 1 :(得分:0)

使用下划线库的简单解决方案:

var list = [
    { city: 'Durham, NC, United States', begin: '09/04/2017', id: 0 },
    { city: 'Raleigh, NC, United States', begin: '09/11/2017', id: 1 },
    { city: 'Durham, NC, United States', begin: '09/25/2017', id: 2 },
    { city: 'Durham, NC, United States', begin: '09/25/2017', id: 3 },
];

var uniqueList = _.uniq(list, function(v) {
return v.x && v.y;
});

console.log(uniqueList);

答案 2 :(得分:0)

您可以使用array#reducearray#some。您可以将所有唯一值存储在新对象中,并使用它来检查新对象是唯一的还是早期对象的副本。

&#13;
&#13;
var places =[{city: "Durham, NC, United States", begin: "09/04/2017", id: 0},{city: "Raleigh, NC, United States", begin: "09/11/2017", id: 1},{city: "Durham, NC, United States", begin: "09/25/2017", id: 2}, {city: "Durham, NC, United States", begin: "09/25/2017", id: 3}];

var uniquePlaces = places.reduce((hash, obj) => {
  let isExist = Object.values(hash).some(v => v.city === obj.city && v.begin === obj.begin);
  return !isExist ? Object.assign(hash, {[obj.id] : obj}) : hash;
}, Object.create(null));

var result = Object.values(uniquePlaces);
console.log(result);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;