2 回答

TA貢獻1798條經驗 獲得超3個贊
const array1 = [
{
props: {
type : 'text',
id : 'item1',
name : 'item1',
value : '@item1@',
},
},
{
props: {
type: 'hidden',
id: 'item2',
name: 'item2',
value: '@item2@',
},
}
];
const array2 = [
{
props: {
type: 'hidden',
id: 'item1',
name: 'item1',
value: '@item1@',
},
}
];
function getUnique(arr, comp) {
const unique = arr
.map(e => e[comp])
// store the keys of the unique objects
.map((e, i, final) => final.indexOf(e) === i && i)
// eliminate the dead keys & store unique objects
.filter(e => arr[e]).map(e => arr[e]);
return unique;
}
const arr = array1.concat(array2);
console.log(getUnique(arr, 'id'));

TA貢獻1859條經驗 獲得超6個贊
你可以
id => object
從第一個數組創建一個 Map遍歷第二個數組,或者
如果尚未在地圖中添加該項目
檢查當前項目是否不是
type: "hidden"
并覆蓋另一個否則丟棄該項目
從 Map 創建一個新數組
const array1 = [
{
props: {
type : 'text',
id : 'item1',
name : 'item1',
value : '@item1@',
},
},
{
props: {
type: 'hidden',
id: 'item2',
name: 'item2',
value: '@item2@',
},
},
{
props: {
type: 'hidden',
id: 'item3',
name: 'item3',
value: '@item3@',
},
}
];
const array2 = [
{
props: {
type: 'hidden',
id: 'item1',
name: 'item1',
value: '@item1@',
},
},
{
props: {
type: 'text',
id: 'item3',
name: 'item3',
value: '@item3@',
},
}
];
//1. create a map from id => object pairs
const map = new Map(array1.map(obj => [obj.props.id, obj]));
//2. go over the second array
array2.forEach(obj => {
if (!map.has(obj.props.id) //not a duplicate
|| obj.props.type !== "hidden") { //is not hidden
//insert
map.set(obj.props.id, obj);
}
});
//3. convert back into array
const merged = [...map.values()];
console.log(merged);
為了記錄,您基本上可以使用相同(或非常相似)的東西,.filter
但您必須O(n)
對每個項目進行查找。Map 確保更快的查找。
添加回答
舉報