Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

61
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!