javascript - 如何推送到嵌套在对象中的数组?
问题描述
我已经为此工作了几个小时,但无法弄清楚。我有一个按类别排序的清单对象,每个类别都是一个任务对象数组。我试图允许用户将任务添加到给定的类别数组,但无法弄清楚。每次我尝试记录数组时,它都会打印出观察者并说“.push”不是一个函数。
我认为问题在于使用变量来获取数组,因为当我在'masterChecklist [“General Cleaning”]'中硬编码时,它会起作用。请帮忙!
** 下面的例子是简化的
var masterChecklist = {
"General Cleaning":
[
{cleaned: false, notes: "", name: 'Empty and sanitize trash bins'},
{cleaned: false, notes: "", name: 'Clean mirrors and windows'},
],
"Home Exterior":
[
{cleaned: false, notes: "", name: 'Wipe and clean all furniture'},
{cleaned: false, notes: "", name: 'Empty the trash bins'},
],
}
SaveTaskDetails("Dust", "Make sure to get the shelves", "General Cleaning")
function SaveTaskDetails(name, notes, category) {
var newTask = {
name: name,
notes: notes,
cleaned: false
}
var category = masterChecklist[category].push(newTask)
}
console.log(masterChecklist);
解决方案
你可以做:
const masterChecklist = {'General Cleaning': [{ cleaned: false, notes: '', name: 'Empty and sanitize trash bins' },{ cleaned: false, notes: '', name: 'Clean mirrors and windows' },],'Home Exterior': [{ cleaned: false, notes: '', name: 'Wipe and clean all furniture' },{ cleaned: false, notes: '', name: 'Empty the trash bins' }]}
const SaveTaskDetails = (name, notes, category) => {
if (!masterChecklist[category]) {
masterChecklist[category] = []
}
masterChecklist[category].push({ name, notes, cleaned: false })
}
SaveTaskDetails('Dust', 'Make sure to get the shelves', 'General Cleaning')
SaveTaskDetails('Dust', 'Make sure to get the shelves', 'New Category')
console.log(masterChecklist)
推荐阅读
- javascript - 如何修复获取json参数并将其发送到url的java脚本函数
- delphi - 挂钩 Delphi TReader.OnFindComponentClass
- java - 无法使用 zipOutputStream 在 java 中压缩文件?
- spring-boot - WebClient 首次请求缓慢的解决方法
- java - 接口与单例中的全局变量
- php - 我如何在我的 laravel5.7 网站中添加 Metas,如标题、描述、关键字
- javascript - 如何使用向量施加不同的力?
- math - Julia - 数组的绝对值
- android - 尝试使用 SharedPreferences 更改颜色,但方法不正确
- asp.net - 如何修复未映射的成员?