Estoy creando una aplicación para tomar notas en React y tengo algunos datos que se ven así. Quiero filtrarlo para que solo queden los objetos que contienen una etiqueta en una matriz, y el resto se elimine.
const obj = { Mon: [ { id: 1, content: 'Some text', tag: 'home' }, { id: 2, content: 'Some text', tag: 'work' }, { id: 3, content: 'Some text', tag: 'project' }, ], Tue: [ { id: 4, content: 'Some text', tag: 'project' }, { id: 5, content: 'Some text', tag: 'moving' }, ], Wed: [ { id: 6, content: 'Some text', tag: 'home' }, { id: 7, content: 'Some text', tag: 'home' }, { id: 8, content: 'Some text', tag: 'work' }, ], }; const filterTags = ['home', 'work'] { Mon: [ { id: 1, content: 'Some text', tag: 'home' }, { id: 2, content: 'Some text', tag: 'work' }, ], Wed: [ { id: 6, content: 'Some text', tag: 'home' }, { id: 7, content: 'Some text', tag: 'home' }, { id: 8, content: 'Some text', tag: 'work' }, ], }; La razón por la que quiero filtrar usando una matriz es porque quiero que un usuario pueda hacer clic en las etiquetas de las notas que quiere ver (estas etiquetas están actualmente almacenadas en useState() ).
Con los datos restantes después del filtrado, planeo mapearlos y representar los elementos relevantes de esta manera:
<> {Object.entries(sortedNotesData).map( ([noteDate, noteContent], i) => ( <div key={i}> <NoteDate noteDate={noteDate} /> <div className="column"> {noteContent .map((note) => ( <> <NoteCard key={note.id} id={note.id} content={note.content} tag={note.tag} /> </> ))} </div> </div> ) )} </> Cualquier sugerencia sobre una forma de mejor práctica para filtrar los datos sin procesar sería genial, incluso si sería mejor manejar el filtrado de datos en una función fuera de render() , o si se puede hacer en línea justo antes de .map() .
Convierta el objeto en una matriz usando Object.entries .
Mapee sobre la matriz anidada y filtre los valores usando la matriz filterTags .
Elimine los días que no tengan elementos coincidentes.
Finalmente, convierta la matriz anidada nuevamente en un objeto usando Object.fromEntries
const obj = { Mon: [ { id: 1, content: "Some text", tag: "home" }, { id: 2, content: "Some text", tag: "work" }, { id: 3, content: "Some text", tag: "project" }, ], Tue: [ { id: 4, content: "Some text", tag: "project" }, { id: 5, content: "Some text", tag: "moving" }, ], Wed: [ { id: 6, content: "Some text", tag: "home" }, { id: 7, content: "Some text", tag: "home" }, { id: 8, content: "Some text", tag: "work" }, ], }, filterTags = ["home", "work"], filteredObj = Object.fromEntries( Object.entries(obj) .map(([key, value]) => [ key, value.filter(({ tag }) => filterTags.includes(tag)), ]) .filter(([, value]) => value.length) ); console.log(filteredObj);También puede conservar los días que no tienen elementos coincidentes simplemente eliminando el último filtro.
const obj = { Mon: [ { id: 1, content: "Some text", tag: "home" }, { id: 2, content: "Some text", tag: "work" }, { id: 3, content: "Some text", tag: "project" }, ], Tue: [ { id: 4, content: "Some text", tag: "project" }, { id: 5, content: "Some text", tag: "moving" }, ], Wed: [ { id: 6, content: "Some text", tag: "home" }, { id: 7, content: "Some text", tag: "home" }, { id: 8, content: "Some text", tag: "work" }, ], }, filterTags = ["home", "work"], filteredObj = Object.fromEntries( Object.entries(obj).map(([key, value]) => [ key, value.filter(({ tag }) => filterTags.includes(tag)), ]) ); console.log(filteredObj);Similar a la respuesta de SSM, pero si no desea incluir días sin resultados
.
const obj = { Mon: [ { id: 1, content: 'Some text', tag: 'home' }, { id: 2, content: 'Some text', tag: 'work' }, { id: 3, content: 'Some text', tag: 'project' }, ], Tue: [ { id: 4, content: 'Some text', tag: 'project' }, { id: 5, content: 'Some text', tag: 'moving' }, ], Wed: [ { id: 6, content: 'Some text', tag: 'home' }, { id: 7, content: 'Some text', tag: 'home' }, { id: 8, content: 'Some text', tag: 'work' }, ], }; const filterTags = ['home', 'work'] //this will hold an object of results let filteredResults = {}; Object.entries(obj).forEach(day => { const name = day[0]; const filtered = day[1].filter(content => filterTags.includes(content.tag)) if (filtered.length > 0) { filteredResults[name] = filtered } }) console.log(filteredResults)