首先,我知道關于這個問題有很多答案,但我對他們有一些問題,這就是為什么我在這個主題上發布另一個問題。
所以這是我的物件陣列:
0: {id: 'lAYOUT', label: 'lAYOUT', items: 'val1'}
1: {id: 'tecst', label: 'tecst', items: 'val1'}
2: {id: 'tecst', label: 'tecst', items: 'val1'}
我試圖過濾掉只有 2 個值,因為陣列中有 2 個相同的物件。我想用items和制作獨特的物品label。
這就是我嘗試這樣做的方式lodash:
const filteredArray = uniq(nestedItems, (item, key, a) => item.items && item.label)
但它仍然讓我回傳所有 3 個元素。
我也試過這樣:
const filteredArray = [...new Set(nestedItems)]
uj5u.com熱心網友回復:
試試這個代碼!
let arr = [{ id: 'lAYOUT', label: 'lAYOUT', items: 'val1' },
{ id: 'tecst', label: 'tecst', items: 'val1' },
{ id: 'tecst', label: 'tecst', items: 'val1' }];
let newArr = arr.filter((value, index, self) =>
index === self.findIndex((t) => (
t.label === value.label && t.items === value.items
))
);
console.log(newArr, 'newArr');
uj5u.com熱心網友回復:
const data = [
{ id: 'lAYOUT', label: 'lAYOUT', items: 'val1' },
{ id: 'tecst', label: 'tecst', items: 'val1' },
{ id: 'tecst', label: 'tecst', items: 'val1' }
];
const unique = (key) =>
[...new Map(data.map(item => [item[key], item])).values()];
console.log(unique('id'));
uj5u.com熱心網友回復:
您可以使用哈希分組按幾個鍵進行過濾:
const data = [{ id: 'lAYOUT', label: 'lAYOUT', items: 'val1' }, { id: 'tecst', label: 'tecst', items: 'val1' }, { id: 'tecst', label: 'tecst', items: 'val1' }];
const unique = Object.values(data.reduce((acc, obj) => {
const hash = `${obj.id}-${obj.label}`;
acc[hash] = obj;
return acc;
}, {}));
console.log(unique);
.as-console-wrapper{min-height: 100%!important; top: 0}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/408125.html
標籤:
