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

106
Vistas
cómo agregar valor a la matriz de objetos a un índice particular en React

Quiero agregar datos a la matriz de objetos al hacer clic en el botón, si el valor del índice no está presente, cree un nuevo objeto y agregue datos

 const [sampleArray, setSampleArray] = useState([{fruit:'', Vegetable:''}]) const addData=(index, value)=> { setSampleArray() }
 on first click : index = 1 & fruit = 'orange' on second click : index = 1 & vegetable = 'brinjal' on third click : index = 2 & fruit = 'Banana' on fourth click : index = 2 & fruit = 'cabbage' <button onClick={addData}> submit </button>

el resultado debería ser así:

[{fruta:'naranja', Verdura:'berenjena'}, {fruta:'Plátano', Verdura:'repollo'}]

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

0

Aquí hay una solución de ejemplo:

 const addData = (index, value) => { const updatedArray = [...sampleArray]; if (!updatedArray[index]) { // Add your data however you want updatedArray.push({}) } else { // Change your data however you want updatedArray[index].fruit = value; } setSampleArray(updatedArray); }
about 4 years ago · Juan Pablo Isaza Denunciar

0

Puede introducir una variable de estado de contador de clics para realizar un seguimiento del número de clics. Y luego use el gancho useEffect para verificar en qué índice se encuentra. Luego configure su sampleArray fruit o Vegetable si aún no se ha configurado. Si aún tiene más datos para el siguiente índice, agregue un nuevo objeto vacío antes de escribir la fruta. Por lo tanto, no solo está limitado a un número fijo de datos.

 function App() { const [sampleArray, setSampleArray] = React.useState([{ fruit: "", Vegetable: "" }]); const data = [{fruit:'orange', Vegetable:'brinjal'}, {fruit:'Banana', Vegetable:'cabbage'}, {fruit:'Apple', Vegetable:'nuts'}]; const [clicks, setclicks] = React.useState(0); React.useEffect(()=>{ if(!clicks) return; const index = Math.floor(clicks/2+0.5); let arr = sampleArray; if(clicks & 1){ //odd if(!arr[index-1] && data[index-1]) arr.push({ fruit: "", Vegetable: "" }) if(!data[index-1]) return; arr[sampleArray.length -1].fruit = data[index-1].fruit; addData(index, arr) }else{ //even if(!data[index-1]) return; arr[sampleArray.length -1].Vegetable = data[index-1].Vegetable; addData(index, arr) } },[clicks]) const addData = (index, value) =>{ setSampleArray([...value]); } return ( <div className="App"> <button onClick={()=>setclicks(clicks+1)}> submit </button> <div> {JSON.stringify(sampleArray)} </div> <div> clicks: {clicks} </div> </div> ); } ReactDOM.render( < App / > , document.getElementById("root"));
 <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id="root"></div>

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