我有如同下列的數組:獲取獨特元素的數組從對象
files = [
{name: 'Lorem', other: true},
{name: 'Foo', other: true},
{name: 'Bar', other: true}
];
files = [
{name: 'Lorem', other: true},
{name: 'Xxxxx', other: true}
];
files = [
{name: 'Lorem', other: true},
{name: 'Foo', other: true},
{name: 'Epic', other: true},
{name: 'Xxxxx', other: true}
];
我試圖獲得有關下劃線的獨特元素的合併數組,但它不工作。這是我的代碼:
function getAllFiles(alldocs) {
var all = [];
_.each(alldocs, function(element) {
all = _.union(all, element.files);
});
return all;
}
但我得到一個重複的項目數組。
看到https://github.com/jashkenas/underscore/issues/2311 –
你很可能http://underscorejs.org/#uniq也與'union' –
的解決方案下面給出的只是'name'屬性的檢查,但可能你想要區分'name'和'other'屬性。循環訪問數組並檢查兩者。如果它只是你想檢查的單個值,你可以用地圖來做,並減少一行。 – MartijnK