【问题标题】:Search through array of objects for case-insensitive partial match and sort results alphabetically在对象数组中搜索不区分大小写的部分匹配并按字母顺序对结果进行排序
【发布时间】:2020-06-04 20:03:02
【问题描述】:

我希望有人能够帮助我或至少指导我寻找答案的主题

我是 React 的新手。我有一个代码允许我过滤项目对象中的列表。这没有问题。但是我想改用准备好的 json 文件,但是当我尝试引用“城市”时,我在 onTextChanged 方法中遇到了一个错误(无法读取未定义的属性“排序”)。我不确定我应该如何与 json 中的下一个级别相关联。如果我们将 CityList 作为项目的定义,我尝试了类似的方法。

this.items.city.sort().filter(...)

这是整个组件

 import React, { Component } from 'react';
    import "./HiddenTownList.css";
    //import CityList from "./JsonCities";

    class HiddenTownList extends Component {
        items = [
            "Warsaw",
            "New York",
            "London"
        ];
        state = {
            suggestion: []
        };

        onTextChanged = (e) => {
            const value = e.target.value;
            let suggestion = [];
            if (value.length > 0) {
                const regex = new RegExp(`^${value}`, 'i');
                suggestion = this.items.sort().filter(v => regex.test(v));
                this.setState(() => ({ suggestion }))
            }
            else {
                this.setState(() => ({ suggestion }));
            }
        }

        renderSuggestions() {
            const { suggestion } = this.state;
            if (suggestion.length === 0) {
                return null;
            }
            else {
                return (
                    <ul>{suggestion.map((city) => <li>{city}</li>)}</ul>
                )

            }
        }

        render() {
            return (
                <>
                    <input onChange={this.onTextChanged}></input>
                    {this.renderSuggestions()}
                </>
            )
        }

    };
    export default HiddenTownList; 

JSON 代码示例

const CityList = [
    {
        "id": "1",
        "city": "Katowice",
        "lat": "50.258415",
        "lng": "19.027545",
        "country": "Poland",
        "admin": "Śląskie"
    },
    {
        "id": "2",
        "city": "Warsaw",
        "lat": "52.25",
        "lng": "21",
        "country": "Poland",
        "admin": "Mazowieckie"
    },
    {
        "id": "3",
        "city": "Łódź",
        "lat": "51.75",
        "lng": "19.466667",
        "country": "Poland",
        "admin": "Łódzkie"
    }]

【问题讨论】:

  • 它尝试在此时未定义的变量上调用 sort() 方法。您确定该值是否正确传递?您是否尝试过 console.log() 并看到了值?
  • 你如何指代城市?在您的示例中没有提到它。
  • 我更改了“项目”中的示例数据,因为当我尝试使用 map 方法在屏幕上显示数据时它们可能会混淆@AbuSufian 一切正常,我尝试测试控制台.log 和调试器来跟踪数据。问题是我不能引用较低的 json 级别的数据。

标签: javascript json reactjs


【解决方案1】:

您正在尝试对城市执行排序功能。这是可变的。这就是它给出未定义值的方式。排序总是对数组字段起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-19
    • 2017-02-28
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 2012-06-25
    • 1970-01-01
    相关资源
    最近更新 更多