停止过滤器(),有可能吗?

时间:2017-09-04 09:45:28

标签: javascript arrays object filter

我有这样的代码:

        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>
        )
    })

如何退出过滤器并转到maping而不是循环遍历所有项目。可能吗?我尝试过休息但继续但没有奏效。

对象键中的数组(项目)是一个带有一堆道具的对象,大约5000千)

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

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

您可以使用slice代替filter来限制数组长度

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

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

答案 2 :(得分:1)

你不能在过滤器之间中断,你必须抛出一个异常,然后如果你想要阻止它就抓住它。而是尝试这个

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