我有一個嵌套的物件陣列,其中包含一些重復值:
[
[
{
name: 'name1',
email: 'email1'
},
{
name: 'name2',
email: 'email2'
}
],
[
{
name: 'name1',
email: 'email1'
}
],
[
{
name: 'name1',
email: 'email1'
},
{
name: 'name2',
email: 'email2'
}
]
]
我想從此資料創建一個新的單個陣列,其中僅包含所有嵌套陣列中存在的物件:
[
{
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
uj5u.com熱心網友回復:
您可以使用第一個子陣列中的物件創建一個 Map,并以它們的 JSON 表示作為鍵(在對其鍵進行排序之后)。然后為 JSON 表示在該映射中的物件過濾下一個子陣列,并將它們放入新映射中。對所有子陣列繼續這樣。最后回傳保留在最后一張地圖中的值:
// 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));
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/508170.html
標籤:javascript 数组 多维数组 javascript 对象