【问题标题】:Stopping filter(), is it possible?停止过滤器(),有可能吗?
【发布时间】:2018-02-12 12:49:47
【问题描述】:

我有这样的代码:

        return Object.keys(items).filter((item, index) => {
        if(index <= this.state.limit)
            return item

        if(index > this.state.limit)
            break? continue to the maping? how?
    }).map( (item, index) => {
        return(
            <div key={index}>
                {item.title}
            </div>
        )
    })

我怎样才能退出过滤器并转到映射而不是循环遍历所有项目。可能吗?我尝试了中断并继续,但没有成功。

对象键中的数组(items)是一个带有一堆props的对象,大约500万)

const items = {
    title2: 'bird',
    title3: 'apple,
    title4 ....
}

我需要返回对象中 first N 个道具的数量,具体取决于 this.state.limit

【问题讨论】:

  • 我们可以看看你的阵列吗?因为您可以简单地使用切片,所以您似乎使用过滤器来获取前 X 个元素...
  • @Salketer 编辑了我的帖子
  • 谢谢。我认为您首先遇到了该对象的问题...您最好拥有一个对象数组,否则您无法确定将显示哪些元素,因为无法保证键顺序。

标签: javascript arrays object filter


【解决方案1】:

您可以使用slice 而不是filter 来限制数组长度

return Object.values(items)
             .slice(0, this.state.limit + 1)
             .map( (item, index) => {
               return (
                 <div key={index}>
                  {item.title}
                 </div>
               )
             })

但您应该记住,对象中属性的顺序是保证的。

【讨论】:

    【解决方案2】:

    只需返回false 获取您不想要的物品:

    return Object.keys(items)
        .filter((item, index) => index <= this.state.limit)
        .map((item, index) => (
            <div key={index}>
                {item.title}
            </div>
        ));
    

    您无法停止 filter 以停止循环,但上面的代码将完美运行。


    如果您只想有效地迭代第一个 N 元素,您可以使用 for 循环:

    // get your array you want to iterate
    const list = Object.keys(items);
    
    // nodes will contain results from (0) to (this.state.limit)
    const nodes = [];
    for (let i = 0; i <= this.state.limit; i++) {
        nodes.push((
            <div key={i}>
                {list[i].title}
            </div>
        ));
    }
    
    return nodes;
    

    注意:如果你的数据是这样的:

    const items = {
        title2: 'bird',
        title3: 'apple',
        // and so on
    }
    

    如果您想打印birdapple 等...,您可能需要使用Object.values 而不是keys

    【讨论】:

      【解决方案3】:

      你不能在过滤器之间中断,如果你想停止它,你必须抛出一个异常,然后再捕获它。试试这个

      if(index > this.state.limit)
          return 1; // return 1 if you want to keep those objects or 0 if you don't
      

      【讨论】:

      • 或者干脆return index &lt;= this.state.limit
      猜你喜欢
      • 2022-11-10
      • 2013-09-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多