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>
CodePudding user response:
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);
}
CodePudding user response:
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>
CodePudding user response:
Instead of pushing text into the arr. You can just manipulate it a bit like maintaining index variables and incrementing the same.
let arr = [];
let index = 0;
function addText() {
let text = document.getElementById('text').value;
const obj = {index, text}
arr.push(obj);
res = document.getElementById('result-text').innerText = JSON.stringify(arr);
index =1
}
<input type="text" id="text" placeholder="Enter a text" />
<input type="submit" onclick="addText()" />
<p id="result-text"></p>
CodePudding user response:
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>
CodePudding user response:
Here's the possible solution:
let arr = [];
function addText() {
let text = document.getElementById('text').value;
let index = arr.length;
arr.push({index:index,text:text});
res = document.getElementById('result-text').innerText = JSON.stringify(arr);
}
<input type="text" id="text" placeholder="Enter a text" />
<input type="submit" onclick="addText()" />
<p id="result-text"></p>
