Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

304
Vistas
No se pueden eliminar objetos de la matriz, react.js

Estoy tratando de eliminar un elemento de un childArray que está anidado en otro Array.

Así es como lo estoy intentando.

 const childArrayHandler = (childData, sub, questionId, data, btnId) => { // Manage color change on click const isInList = selectedBtnList.some((item) => item === btnId) if (isInList) { onSelectedBtnListChange(selectedBtnList.filter((item) => item !== btnId)) } else { onSelectedBtnListChange([...selectedBtnList, btnId]) } // Manage childData Array // copy data to mutable object const currentChildData = [...childData] const hasId = currentChildData.find(({ id }) => sub.id === id) if (!hasId) { // add item to childArray if same index is not available in the childArray const newChild = { id: sub.id, sub_question: sub.sub_question, weightage: sub.weightage } currentChildData.push(newChild) setChildDataOnChange((current) => [...current, newChild]) } else if (hasId) { // remove item from childArray if same index is available in the childArray const indexOfChild = currentChildData.indexOf(hasId) // console.log('currentChildData', currentChildData, 'indexOfChild', indexOfChild) currentChildData.slice(indexOfChild, 1) setChildDataOnChange(currentChildData) } const newData = [...data] // find parent of the child const parent = newData.find(({ parentId }) => questionId === parentId) // find index of parent const indexOfParent = newData.indexOf(parent) // update data with child related to parent newData[indexOfParent].child = currentChildData onDataChange(newData) localStorage.setItem('deviceReport', JSON.stringify(newData)) }

El problema está en el bloque else if , quiero que si hay un índice de objeto disponible en el elemento secundario, entonces debería eliminarlo de la matriz. Por lo que puedo ver, estoy usando el enfoque correcto como se sugiere en otros artículos, pero me falta algo que no puedo ver en este momento. Pero no es capaz de encontrar el resultado adecuado. Si me consuelo no cambia nada. significa no eliminar ningún elemento de la matriz si el índice ya está allí.

Entonces, ¿cómo puedo solucionar esto, o qué podría estar haciendo mal? ¿Hay alguna otra forma de hacerlo? Por favor, menciónelo también. Gracias

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Tienes el problema con esta rebanada

 currentChildData.slice(indexOfChild, 1)

No inicializa una nueva matriz para usted ( inmutabilidad de React )

La solución podría ser

 currentChildData = currentChildData.slice(0, indexOfChild).concat(currentChildData.slice(indexOfChild + 1))

Si cree que es demasiado complicado, puede usar el filter en su lugar

 currentChildData = currentChildData.filter((item) => item !== hasId) //`hasId` is your found item with `find`

El segundo problema aquí es

 newData[indexOfParent].child = currentChildData

No puede asignar un valor a un objeto mutado

La forma correcta debe ser

 newData = newData.map((item) => item === parent ? {...item, child: currentChildData} : item)

El código completo

 const childArrayHandler = (childData, sub, questionId, data, btnId) => { // Manage color change on click const isInList = selectedBtnList.some((item) => item === btnId) if (isInList) { onSelectedBtnListChange(selectedBtnList.filter((item) => item !== btnId)) } else { onSelectedBtnListChange([...selectedBtnList, btnId]) } // Manage childData Array // copy data to mutable object let currentChildData = [...childData] const hasId = currentChildData.find(({ id }) => sub.id === id) if (!hasId) { // add item to childArray if same index is not available in the childArray const newChild = { id: sub.id, sub_question: sub.sub_question, weightage: sub.weightage } currentChildData.push(newChild) setChildDataOnChange((current) => [...current, newChild]) } else { // console.log('currentChildData', currentChildData, 'indexOfChild', indexOfChild) currentChildData = currentChildData.filter((item) => item !== hasId) setChildDataOnChange(currentChildData) } //let newData = [...data] // find parent of the child //const parent = newData.find(({ parentId }) => questionId === parentId) // update data with child related to parent //newData = newData.map((item) => item === parent ? {...item, child: currentChildData} : item) //shorter version const newData = data.map((item) => item.parentId === questionId ? {...item, child: currentChildData} : item) onDataChange(newData) localStorage.setItem('deviceReport', JSON.stringify(newData)) }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda