我想構建一個帶有復選框的自更新過濾器。
我的資料:
const Shooting= [
{
name: "John & Johna ",
tag: ["wedding", "couple"],
img: [ src1 , src2, ...] //irrelevant
},
{
name: "Mario & Marie",
tag: ["couple", "NSFW"],
img: [ src1 , src2, ...] //irrelevant
},
];
export default Shooting;
我的輸出應該是這樣的:
Filter:
[]wedding
[]couple
[]NSFW
// [] are checkboxes, "couple" is a duplicate in the array
我的代碼思路:
- 將所有標簽放入一個新陣列中
- 構建函式以從新陣列中洗掉重復項
- 使用 map-function -> Obj.map((tag))=>{...} 列出過濾后的陣列
我的問題:
如何獲取新串列中的所有標簽?
uj5u.com熱心網友回復:
你可以嘗試[...new Set(Shooting.map(({ tag }) => tag).flat(1))],
->Shooting.map(({tag}) => tag)將回傳陣列中的標簽。
-> 然后我們可以使用array.flat()來連接標簽。
-> 然后要洗掉重復項,我們使用...new Set(...).
const App = () => {
const Shooting = [
{
name: "John & Johna ",
tag: ["wedding", "couple"],
img: ["src1", "src2"]
},
{
name: "Mario & Marie",
tag: ["couple", "NSFW"],
img: ["src1", "src2"]
}
];
const result = [...new Set(Shooting.map(({ tag }) => tag).flat(1))];
return <div>
<h2> Filter: </h2>
<ul>
{
result.map((list, i) => <div key={i}><input type="checkbox" /> {list} </div> )
}
</ul>
</div>
}
// Render it
ReactDOM.createRoot(
document.getElementById("root")
).render(
<App />
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
uj5u.com熱心網友回復:
創建reduce函式set
const Shooting= [
{
name: "John & Johna ",
tag: ["wedding", "couple"],
},
{
name: "Mario & Marie",
tag: ["couple", "NSFW"],
},
];
const result = Shooting.reduce((acc, item) => {
return [ ...new Set([...acc, ...item.tag]) ]
}, [])
console.log(result)
uj5u.com熱心網友回復:
您可以使用 reducer 獲取所有唯一標簽
const array = [
{
name: "name1",
tag: ["tag1", "tag2"],
},
{
name: "name2",
tag: ["tag2", "tag3"],
},
];
const tags = array.reduce((acc, item) => {
item.tag.forEach((tag) => {
if (!acc.includes(tag)) {
acc.push(tag);
}
});
return acc;
}, []);
然后你可以用你的標簽做任何你想做的事。祝你好運!
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/537313.html
標籤:反应数组目的筛选
