【问题标题】:Filter with map but keep the indice使用地图过滤但保留索引
【发布时间】:2018-07-04 23:41:35
【问题描述】:

我想过滤然后映射对象数组,但是当这样做时过滤器会创建一个新数组并给我不同的索引,可以使用过滤器来做到这一点,或者我应该使用其他方式。

this.props.todos = [
          {
            task:'Daily meet',
            status:'incomplete'
          },
          {
            task:'Play videogame'
            status:'complete'
          }
]

this.props.todos.filter(todos => todos.status === 'complete').map((todos, i) => {

 return (<p>{todos.status} - Everythin Ok</p>)
 //here i got i = 0

}));
this.props.todos.filter(todos => todos.status === 'incomplete').map((todos, i) => {

  return (<p>{todos.status} - You have some task incomplete</p>)
  //and here i got i = 0 too i wanna this to be like the original array
}));

【问题讨论】:

  • 不要使用过滤器,只使用map。检查状态,如果是另一个,则返回null 而不是&lt;p&gt;
  • 你在一个数组中有两个元素,看起来你想要两个数组,每个数组都有一个元素。如果每个新数组只有一个元素,它怎么会有相同的索引呢?此外,您没有保存过滤器的返回值。它没有就地过滤,所以目前你的代码并没有真正做任何事情。

标签: javascript reactjs ecmascript-6 babeljs


【解决方案1】:

只需使用map,无需过滤。您可以像这样返回任一组件:

this.props.todos = [
  {
    task: 'Daily meet',
    status: 'incomplete'
  },
  {
    task: 'Play videogame'
    status: 'complete'
  }
]

this.props.todos.map(todo => {
  if (todo.status === 'complete') {
    return (<p>{todo.status} - Everythin Ok</p>);
  }

  if (todo.status === 'incomplete') {
    return (<p>{todo.status} - You have some task incomplete</p>);
  }

  return null;
})

【讨论】:

    猜你喜欢
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 2018-08-25
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多