【问题标题】:How to get the filtered index when chaining filtering and map methods链接过滤和映射方法时如何获取过滤后的索引
【发布时间】:2016-06-11 14:23:57
【问题描述】:

假设我们有一个包含 x 个条目的对象数组。

条目的 E.G 是

{
 name: 'someone',
 age: 22,
 modified: true
}

现在我们要过滤条目,以便我们可以通过使用过滤器方法获得所有包含modified = true的条目。过滤后,我们会将结果映射到 div。

例如:

return this.props.entries.filter((entry) => {
  return entry.modified === true;
}).map((displayedEntry, index) => {
  return (
    <tr>
      <td>{index + 1}</td>
      <td>displayedEntry.name</td>
    </tr>
  );
});

问题在于显示的索引对应于被过滤的条目数量:如果修改了 4 个项目,我们的索引 = [0,1,2,3]。

我的问题是我们如何传递原始数组中项目的索引,而不是映射数组中的项目索引。

所以如果 index: 5,10 处的项目被修改,我可以在映射结果时传递这些索引?

我希望我解释清楚了。

【问题讨论】:

    标签: javascript reactjs functional-programming ecmascript-6


    【解决方案1】:

    如果您不想破坏原始对象,请使用投影:

        return this.props.entries
        .map((entry, index) => {
            return {
                entry: entry,
                index: index
            };
        })
        .filter((proj) => {return proj.entry.modified === true;})
        .map(proj => {
            return (
                <tr>
                  <td>{proj.index + 1}</td>
                  <td>proj.entry.name</td>
                </tr>
            );
        });
    

    【讨论】:

      【解决方案2】:

      这有点难看,但你可以这样做:

      return this.props.entries.
        map((entry, index) => {
          entry.displayIndex = index;
          return entry;
        }).
        filter((entry) => {
          return entry.modified === true;
        }).
        map((displayedEntry, index) => {
          return (
            <tr>
              <td>{displayedEntry.displayIndex + 1}</td>
              <td>displayedEntry.name</td>
            </tr>
          );
        });
      

      【讨论】:

      • 这是我最初做的,但想避免修改条目。
      猜你喜欢
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      • 2017-12-09
      • 2018-03-26
      • 2015-09-07
      • 1970-01-01
      • 2022-07-06
      • 1970-01-01
      相关资源
      最近更新 更多