Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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"}]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading