本文介绍了javascript - 基于多个属性在数组中查找唯一对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要根据以下 2 个属性从数组中找到唯一对象.当class"和fare"匹配时,我需要提取唯一值并将它们放入结果数组中.
I need to find unique objects from array based on 2 properties as below. When "class" and "fare" match, I need to pull out unique values and get them in results array.
来源:
var arr = [{class:"second", fare: "a"},
{class:"second", fare: "b"},
{class:"first", fare: "a"},
{class:"first", fare: "a"},
{class:"second", fare: "a"},
{class:"first", fare: "c"}
]
预期结果:
var result = [{class:"second", fare: "a"},
{class:"second", fare: "b"},
{class:"first", fare: "a"},
{class:"first", fare: "c"}
]
我在 SO 中查看并能够找到基于一个属性过滤的答案(按属性创建唯一对象数组),但无法根据 2 个属性找到哪些可以执行.
I looked over in SO and was able to find answer which is filtered based on one property (Create array of unique objects by property), but couldn't find which could do based on 2 properties.
推荐答案
您可以为哈希表构建组合键并过滤给定数组.
You could build a combined key for the hash table and filter the given array.
var arr = [{ class: "second", fare: "a" }, { class: "second", fare: "b" }, { class: "first", fare: "a" }, { class: "first", fare: "a" }, { class: "second", fare: "a" }, { class: "first", fare: "c" }],
result = arr.filter(function (a) {
var key = a.class + '|' + a.fare;
if (!this[key]) {
this[key] = true;
return true;
}
}, Object.create(null));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
没有(错误)使用.
The same without (mis)using thisArg
of Array#filter
.
var array = [{ class: "second", fare: "a" }, { class: "second", fare: "b" }, { class: "first", fare: "a" }, { class: "first", fare: "a" }, { class: "second", fare: "a" }, { class: "first", fare: "c" }],
seen = Object.create(null),
result = array.filter(o => {
var key = ['class', 'fare'].map(k => o[k]).join('|');
if (!seen[key]) {
seen[key] = true;
return true;
}
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
这篇关于javascript - 基于多个属性在数组中查找唯一对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!