I'm trying to create a function that deletes an object within a nested array of an object which is within an array...
How would I delete one of the schedules by date?
state = {
children: [
{
id: 1,
firstName: 'Bella',
lastName: 'Laupama',
profile: 'child_care',
schedules: [
{
date: '25 December, 2018',
parent: 'Chris',
activity: 'Christmas'
},
{
date: '28 December, 2018',
parent: 'Mischa',
activity: 'Christmas with Malane Whanau'
},
{
date: '31 December, 2018',
parent: 'Laura',
activity: 'New Years Eve'
},
{
date: '1 January, 2019',
parent: 'Laura',
activity: 'New Years Day'
}
]
}
]
}
Would something like this work?...
delSched = (firstName, date) => {
let children = [...this.state.children]
let findChild = children.find(child => child.firstName == firstName)
let newState = findChild.filter(sched => sched.date !== date)
this.setState({
children: newState
})
}
UPDATE:
Even though most of these solutions would most probably work, the one I could get working was thank you to @Marius. I used a modified version of his code.
delSched = (firstName, date) => {
var children = this.state.children
for (var i = 0; i < children.length; i++) {
var child = this.state.children[i]
if (child.firstName == firstName) {
//Loop through the schedules
for (var k = 0; k < child.schedules.length; k++) {
var schedule = child.schedules[k]
//remove schedule if date == date
if (schedule.date == date) {
child.schedules.splice(k, 1)
}
this.setState({children})
}
}
}
}