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>
>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);
}