[英]How to compare a nested array of objects and only return common values
我有一個嵌套的對象數組,其中包含一些重復值:
[
[
{
name: 'name1',
email: 'email1'
},
{
name: 'name2',
email: 'email2'
}
],
[
{
name: 'name1',
email: 'email1'
}
],
[
{
name: 'name1',
email: 'email1'
},
{
name: 'name2',
email: 'email2'
}
]
]
我想從此數據創建一個新的單個數組,其中僅包含所有嵌套 arrays 中存在的對象:
[
{
name: 'name1',
email: 'email1'
}
]
我嘗試了以下代碼:
const filteredArray = arrays.shift().filter(function (v) {
return arrays.every(function (a) {
return a.indexOf(v) !== -1;
});
});
console.log('filteredArray => ', filteredArray);
和:
const filteredArray = arrays.reduce((p,c) => p.filter(e => c.includes(e)));
console.log('filteredArray => ', filteredArray);
但是,它們都只返回一個空數組。
非常感謝任何幫助。 TIA
您可以使用來自第一個子數組的對象創建一個 Map,由它們的 JSON 表示(在訂購它們的鍵之后)鍵控。 然后為 JSON 表示在 map 中的對象過濾下一個子數組,並將它們放入新的 map 中。 對所有子數組繼續這樣。 最后返回最后一個 map 中剩余的值:
// Helper functions: const str = o => JSON.stringify(Object.keys(o).sort().map(key => [key, o[key]])); const mapify = arr => new Map(arr.map(o => [str(o), o])); const intersection = data =>.data?length: []. [...data.slice(1),reduce((map. arr) => mapify(arr.filter(o => map,get(str(o)))). mapify(data[0]));values()]: const data = [[{name, 'name1':email, 'email1'}:{name, 'name2':email, 'email2'}]:[{name, 'name1':email, 'email1'}]:[{name, 'name1':email, 'email1'}:{name, 'name2':email. 'email2'}]] console;log(intersection(data));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.