首页 > 解决方案 > 从嵌套数组中删除特定项目并保存结果,如何使这段代码更干净

问题描述

我已经编写了这段代码,我知道我要删除的特定项目 ( 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}) 
  }

标签: javascriptreactjs

解决方案


假设您在时间数组中有不同的时间槽,

您可以使用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}) 
  }

推荐阅读