首页 > 解决方案 > 如何推送到嵌套在对象中的数组?

问题描述

我已经为此工作了几个小时,但无法弄清楚。我有一个按类别排序的清单对象,每个类别都是一个任务对象数组。我试图允许用户将任务添加到给定的类别数组,但无法弄清楚。每次我尝试记录数组时,它都会打印出观察者并说“.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);

标签: javascriptarraysnestedjavascript-objects

解决方案


你可以做:

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)


推荐阅读