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

63
Vistas
adding text as object to array

The following program will add the text entered in input to an array and display the array in a p tag. when the user press submit, the text will be added to the array. I need to add it as an object containing index and text.

Currently, the array will look like: ['a', 'b', 'c']

I need to the array to look like: [{"index": 0, "text": "a"}, {"index": 1, "text": "b"}]

let arr = [];
function addText() {
    let text = document.getElementById('text').value;
    arr.push(text);
    res = document.getElementById('result-text').innerText = arr;
}
<input type="text" id="text" placeholder="Enter a text" />
<input type="submit" onclick="addText()" />

<p id="result-text"></p>

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

0

Simply do

let arr = [];
function addText() {
    let text = document.getElementById('text').value;
    arr.push({ index: arr.length, text });
    res = document.getElementById('result-text').innerText = JSON.stringify(arr);
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Just create the object and store it in an array

let arr = [];
function addText() {
    let text = document.getElementById('text').value;
    let textObj = {
                     index: arr.size,
                     text: text
                  }
    arr.push(textObj);
    res = document.getElementById('result-text').innerText = arr;
}
<input type="text" id="text" placeholder="Enter a text" />
<input type="submit" onclick="addText()" />

<p id="result-text"></p>

about 4 years ago · Juan Pablo Isaza Denunciar

0

Just use map:

function addText() {
    const text = document.getElementById('text').value;
    const arr = text.split(',');
    const result = arr.map((text, index) => ({index, text}))
    document.getElementById('result-text').innerText = JSON.stringify(result);
}
<input type="text" id="text" placeholder="Enter a text" />
<input type="submit" onclick="addText()" />

<p id="result-text"></p>

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