【问题标题】:Filter and map and keep original过滤和映射并保持原始
【发布时间】:2020-02-02 10:01:30
【问题描述】:

我有以下结构:

this.pronos = [{
    "id": 1,
    "eventname": "EVENT1",
    "round": "EVENT1-1",
    "factor": 1,
    "matchPassed": 10,
    "matchs": [{
        "eq1": "EQ1",
        "eq2": "EQ2",
        "scoreEq1": 0,
        "scoreEq2": 3,
        "passed": true,
        "stats": {
            "domicile": 35.29,
            "exterieur": 35.29,
            "nul": 29.41,
            "boosted": 1
        },
        "date": 20190809,
        "friendlyDate": "Vendredi  9 ao\u00fbt 2019 20:45",
        "pronos": [{
            "matchId": 10,
            "userId": 1,
            "username": "Marcel",
            "points": 0,
            "validation": true,
            "pronoEq1": 1,
            "pronoEq2": 0,
            "booster": 0,
            "MR": 0
        },
        ...
        ]
    },
    ...
    ],
},
    ...
]

我想保留原始数组并返回这个过滤和映射的数组。

getNextPronos() {
    return this.pronos.filter(event => {
      return event.matchs
        .some(match => {
          return match.date >= this.recentDate;
        });
    })
      .map(event => {
        event.matchs = event.matchs.filter(match => {
          return match.date >= this.recentDate;
        });
        return event;
      }).filter((event) => {
        return event.matchs.length > 0;
      });
  }

我不想声明新数组,因为this.pronos稍后会被修改。

【问题讨论】:

  • FWIW:JSON 是一种用于数据交换的文本表示法(More here.) 如果您正在处理 JavaScript 源代码,而不是处理 string,那么您就不是在处理 JSON。
  • 所以目前的问题是您正在修改 event 对象并且您不想这样做?

标签: json dictionary filter


【解决方案1】:

如果我对您的理解正确,那么您目前的问题是您正在修改 event 对象,但您希望保持它们不变。如果是这样:

getNextPronos() {
    return this.pronos
        // Only events where at least one match is after the date
        .filter(({matchs}) => matchs.some(({date}) => date >= this.recentDate))
        // Map to new event objects with filtered `matchs`
        .map(event => ({
            ...event,
            matchs: event.matchs.filter(({date}) => date >= this.recentDate)
        }));
}

这会在matchs 中进行一次部分循环,以查看是否有任何匹配在日期之后,然后再进行第二次完整循环以过滤掉日期之前的匹配。这对我来说似乎很好。另一种方法是在过滤掉一些事件之前为所有事件创建新的事件对象,如下所示:

getNextPronos() {
    return this.pronos
        // Map to new event objects with filtered `matchs`
        .map(event => ({
            ...event,
            matchs: event.matchs.filter(({date}) => date >= this.recentDate)
        }))
        // Filter out the (new) events that have no `matchs`
        .filter(({matchs}) => matchs.length);
}

旁注:“match”的复数形式是“matches”(带有“e”)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    相关资源
    最近更新 更多