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

338
Vistas
¿Cómo agregar todos los datos de los objetos en una matriz vacía?

En un proyecto React, quiero agrupar ciertos registros en una matriz vacía, para pasar a alguna función. Entonces, al marcar el componente de la casilla de verificación, puedo obtener la identificación del registro que quiero comparar con la matriz de datos. Mi preocupación es enviar todos los registros verificados a una matriz vacía recién creada, para pasarlos a alguna función. He revisado varias publicaciones, pero no obtuve ningún resultado satisfactorio. Consulte el siguiente código.

 const newAllData = [{testId:123, dataId:"44", cycleId:"5050", asset:"N"}, {testId:323, dataId:"54", cycleId:"6660", asset:"N"}, {testId:444, dataId:"44", cycleId:"4340", asset:"Y"}, {testId:134, dataId:"40", cycleId:"5150", asset:"N"}, {testId:222, dataId:"42", cycleId:"5050", asset:"Y"}, {testId:552, dataId:"38", cycleId:"3244", asset:"Y"}, ] const [newArray, setNewArray] = useState([]) // Here I get id of the reocord checked const getArray = (id) => { //Here I find that particular record from data above const newObj = newAllData?.find(d => d.testId == id); var arrayData = []; arrayData.push(...newObj); setNewArray(arrayData) } console.log("NEW ARRAY", newArray) return <> <CheckboxComp getArrayData={getArray} /> </>;

Aquí solo se está llenando un registro en newArray. ¿Cuál es el enfoque correcto para obtener todos los registros?

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

0

Cuando establece el estado con el objeto encontrado, debe incluir el estado anterior :

 setNewArray([...newArray, found]);

PERO: también debe incluir una condición basada en si la casilla está marcada o no. Si está marcado, agréguelo al estado como se indicó anteriormente. Si no está marcado, filter desde el estado newArray .

 const { useEffect, useState } = React; // Pass in some data function App({ data }) { // Set the state const [ newArray, setNewArray ] = useState([]); function handleChange(e) { // Get `value` and `checked` from the box const { value, checked } = e.target; // If the box is checked add it to the state // Note: we coerce the value to a number from a string // because we use a equality check `===`, and the value of // `testId` is a number if (checked) { const found = data.find(obj => obj.testId === +value); if (found) setNewArray([...newArray, found]); } // If the box is not checked remove it from the state if (!checked) { const filtered = newArray.filter(obj => obj.testId !== +value); setNewArray(filtered); } } // Log the change in state for clarification useEffect(() => { console.log(JSON.stringify(newArray)); }, [newArray]); return ( <div> <CheckboxComp data={data} handleChange={handleChange} /> </div> ); } function CheckboxComp({ data, handleChange }) { return ( <div> {data.map(obj => { const { testId } = obj; return ( <label for={testId}> {testId} <input name={testId} type="checkbox" value={testId} onChange={handleChange} /> </label> ); })} </div> ) } const data=[{testId:123,dataId:"44",cycleId:"5050",asset:"N"},{testId:323,dataId:"54",cycleId:"6660",asset:"N"},{testId:444,dataId:"44",cycleId:"4340",asset:"Y"},{testId:134,dataId:"40",cycleId:"5150",asset:"N"},{testId:222,dataId:"42",cycleId:"5050",asset:"Y"},{testId:552,dataId:"38",cycleId:"3244",asset:"Y"}]; ReactDOM.render( <App data={data} />, document.getElementById('react') );
 body { font-size: 1.1em; } label { margin-right: 0.5em; padding: 0.2em; } label:hover { background-color: #ffffa0; } [type="checkbox"]:hover { cursor: pointer; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Puede hacer fácilmente una matriz desde un objeto con el método Array.from() :

 Array.from(object, (element, index) => { /* … */ } )
about 4 years ago · Juan Pablo Isaza Denunciar

0

por favor asigne var arrayData = []; fuera de la función getArray

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