javascript - 从嵌套数组中删除特定项目并保存结果,如何使这段代码更干净
问题描述
我已经编写了这段代码,我知道我要删除的特定项目 ( timeslot
) 以及该特定项目所属的公司 ( name
)
我的数据如下所示:
this.state.data = [
{name: :name1', times: [timeslot1, timeslot2, timeslot3]},
{name: :name2', times: [timeslot1, timeslot2, timeslot3]},
{name: :name3', times: [timeslot1, timeslot2, timeslot3]},
]
有没有办法让这段代码更干净?我觉得它有点冗长或多余:
deleteTime (timeslot, name) {
const newState = this.state.data.map(company => {
if (name === company.name) {
let newTimes = company.times.filter(time => {
return time.dateUTCString !== timeslot.dateUTCString
})
company.times = newTimes
return company
}
return company
})
this.setState({data: newState})
}
解决方案
假设您在时间数组中有不同的时间槽,
您可以使用splice
函数删除数组中数据匹配的索引处的元素:
deleteTime (timeslot, name) {
const newState = this.state.data.map(company => {
if (name === company.name) {
company.times.splice(company.times.indexOf(time), 1);
}
return company
})
this.setState({data: newState})
}
推荐阅读
- ruby-on-rails - 排除数组中数字 1 的重复
- python - 使用 PyInstaller 创建了一个桌面应用程序,但它在 Windows 上不起作用
- javascript - D3.js:放错位置的标签
- doctrine-orm - Doctrine/MySQL mediumtext + 不必要的 ALTER TABLEs
- javascript - 如何将 Object.keys().map() 函数中的参数设置为新对象中的键?
- javascript - 可在多个容器/网格之间拖动的元素
- reactjs - 在反应应用程序中导入图像的问题
- python - 有没有办法在 for 循环中创建具有相同功能但具有不同属性的按钮?
- pyomo - 如何从 Pyomo 中的 AbstractModel 打印到实例的文件参数?
- formatting - Jupyter 笔记本标题,无编号