【问题标题】:Search JS array without losing index - Working Codepen Demo uses fetch() and Alpine.js在不丢失索引的情况下搜索 JS 数组 - 工作 Codepen Demo 使用 fetch() 和 Alpine.js
【发布时间】:2021-08-09 08:21:27
【问题描述】:

我在这里有一个可用的 CodePen 演示:https://codepen.io/JosephAllen/pen/vYmQpWL?editors=0010

这个演示:

  1. 从 API 获取用户
  2. 根据“点”属性对列表进行排序
  3. 然后使用索引显示排序列表作为“排名”。换句话说,如果您的索引为零,那么您就是第一名。

有一个用于搜索和过滤列表的输入字段,但过滤数组会为每个用户创建一个新索引——这破坏了排名的整个想法。

如何在不为用户创建新索引的情况下保持排名和搜索功能?

如果我是 API 的作者,我只会将排名作为属性包含在内,但我不是。

我的获取函数:

getUsers() {
    fetch(`https://trafficthinktank.com/wp-json/mjtw/v1/community`)
        .then((res) => res.json())
        .then((data) => {
            this.isLoading = false;
            this.users = data.sort((a, b) => b.points - a.points);
            // this.users = this.users.map(user => ({ visible: true, ...user }));
            console.log(this.users);
        });
    0;
}

我的过滤功能:

get filteredUsers() {
    if (this.search === "") {
        return this.users;
    }

    return this.users.filter((item) => {
        return item.name.toLowerCase().includes(this.search.toLowerCase());
    });
}

【问题讨论】:

    标签: javascript fetch codepen alpine.js


    【解决方案1】:

    索引不能保持不变,因为在其索引序列中不能有一个缺少数字的数组。不过,您可以简单地映射您的数组并将索引保​​留在里面。看看这个,可能会有所帮助:

    getUsers() {
        fetch(`https://trafficthinktank.com/wp-json/mjtw/v1/community`)
            .then((res) => res.json())
            .then((data) => {
                this.isLoading = false;
                this.users = data.sort((a, b) => b.points - a.points);
                // this.users = this.users.map(user => ({ visible: true, ...user }));
                this.users = this.users.map((entity, index) => ({index, entity}));
                console.log(this.users);
            });
        0;
    }
    

    然后你可以像这样过滤

    get filteredUsers() {
        if (this.search === "") {
            return this.users;
        }
    
        return this.users.filter((item) => {
            return item.entity.name.toLowerCase().includes(this.search.toLowerCase());
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-09
      • 2011-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-05
      • 2021-11-13
      相关资源
      最近更新 更多