Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

62
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda