user2371684
user2371684

Reputation: 1555

pushing new to a array as a object

I need to understand how to push a couple of key value pairs into array which is in a object.

The object is the following:

const todos = [{
  text: 'Order airline tickets',
  completed: false
},{
  text: 'Vaccine appointment',
  completed: true
}, {
  text: 'Order Visa',
  completed: true
}, {
  text: 'Book hotell',
  completed: false
}, {
  text: 'Book taxi to airport',
  completed: true
}]

I have created a html page with a form and text input to create new items the array:

<form action="" id="addTodo">
 <input type="text" name="inputTodo" placeholder="Insert new todo">
 <button>Add Todo</button> 
 </form>

The js code is the following:

//Variable to store value from textbox for new todo
let newTodo = ''
let status = false
//Insert new todo
document.querySelector('#addTodo').addEventListener('submit', function (e) {
    e.preventDefault()
    newTodo = e.target.elements.inputTodo.value
    //console.log(newTodo)
})

The completed value for a new todo will always be false. I have a separate function that loops through the object and displays it in a div with p tags for the text part and radio buttons for completed status false or true.

What I need to learn is how to insert the value of the form and push it into todos.text and take the hard coded value of false and push it into todos.completed.

thanks

Upvotes: 0

Views: 128

Answers (2)

Mamun
Mamun

Reputation: 68933

You have to target the input element to get the value. Then form the object with the value and use Array.prototype.push() to push the object in the array:

document.querySelector('[name="inputTodo"]').value

const todos = [{
  text: 'Order airline tickets',
  completed: false
},{
  text: 'Vaccine appointment',
  completed: true
}, {
  text: 'Order Visa',
  completed: true
}, {
  text: 'Book hotell',
  completed: false
}, {
  text: 'Book taxi to airport',
  completed: true
}]

let newTodo = ''
let status = false
//Insert new todo
document.querySelector('#addTodo').addEventListener('submit', function (e) {
    e.preventDefault()
    newTodo = document.querySelector('[name="inputTodo"]').value;
    todos.push({text: newTodo, completed: false});
    console.log(todos)
})
<form action="" id="addTodo">
 <input type="text" name="inputTodo" placeholder="Insert new todo">
 <button>Add Todo</button> 
 </form>

Upvotes: 0

Shomz
Shomz

Reputation: 37701

Should be like this:

todos.push({
    text: e.target.elements.inputTodo.value,
    completed: false
});

or, if you want to use your temporary vars:

todos.push({
    text: newTodo,
    completed: status
});

you can even define a new temporary object and push it instead:

var newTodoObject = {
    text: newTodo,
    completed: status
}
todos.push(newTodoObject);

Upvotes: 2

Related Questions