【问题标题】:Multi Level JSON Filter多级 JSON 过滤器
【发布时间】:2020-01-07 17:34:07
【问题描述】:

所以我有这个 json:

this.state = {
  projects: [{
    id: 10,
    name: "Project 10",
    runTimes: [{
      id: 186,
      name: "Do Homeworks",
      start: "2020-W01",
      end: "2020-W09",
      project: 10,
      users: [{
        id: 1,
        name: "Sander Cokart",
        runTime: [
          186
        ]
      }]
    }],
    hidden: false
  }, ]
}

我希望根据 runTimes.start & end 进行过滤,

我已经试过了:

    const filtered = array.filter((project) => {
        if (!project.hidden) {
            if (project.runTimes.filter((runTime) => {
                if (moment(runTime.start).isSameOrAfter(context.searchFrom) &&
                    moment(runTime.end).isSameOrBefore(context.searchTo)) {
                    return runTime;
                }
            }).length > 0) {
                return project;
            }
        }
    });

遗憾的是,在项目对象 RunTimes 数组中存在第二个 RunTime 时它不起作用。

有人有想法吗?

【问题讨论】:

  • arrayarray.filter 中的值是多少?和this.state.projects.filter一样吗?
  • 是的,确实是 array = this.state.projects

标签: arrays json reactjs filter momentjs


【解决方案1】:

过滤器功能有点偏离。我认为过滤器周围的 if 语句令人困惑,我会选择更简单的东西。这对我有用:

const result = array.projects.filter((project) => {
  return !project.hidden && project.runTimes.filter(runTime => {
    return moment(runTime.start).isSameOrAfter("2020-W01") &&
      moment(runTime.end).isSameOrBefore("2020-W12")
  })
});

【讨论】:

  • 遗憾的是,每当状态在反应中更新时,这并不会清除数组中的任何过滤项。因此,虽然它返回 false,但它不会更新在过滤器之前仍然包含相同项目的数组
  • 所以在最后一次返回之后需要下面的返回时刻(runTime.start).isSameOrAfter("2020-W01") && moment(runTime.end).isSameOrBefore("2020-W12") } ).长度 > 0;但即便如此,它也只会在运行时数组中的第一个超出范围时隐藏
  • 您是否尝试过使用Array.prototype.some() 代替带有长度检查的过滤器?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多