将new作为对象推入数组

时间:2019-01-02 11:52:19

标签: javascript

我需要了解如何将几个键值对推入对象中的数组。

对象如下:

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

我创建了一个带有表单和文本输入的html页面,以创建数组的新项目:

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

js代码如下:

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

新待办事项的完成值始终为false。 我有一个单独的函数,该函数循环遍历该对象,并在div中将其显示为div,其中p标记为文本部分,单选按钮显示完整状态为false或true。

我需要学习的是如何插入表单的值并将其推入todos.text中,并采用false的硬编码值并将其推入todos.completed。

谢谢

2 个答案:

答案 0 :(得分:2)

应该是这样的:

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

或者,如果您想使用临时变量:

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

您甚至可以定义一个新的临时对象并将其推送:

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

答案 1 :(得分:0)

您必须定位输入元素以获取值。然后使用值形成对象并使用Array.prototype.push()将对象推入数组:

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>