【问题标题】:Searching through array gives no results通过数组搜索没有结果
【发布时间】:2018-10-05 21:33:15
【问题描述】:

我正在创建一个网站,该网站将显示某个地区的所有公共厕所(用于学校项目)。我正在导入一个 JSON 文件,对其进行解析并将其命名为“toiletData”。我想做的是让一个对象负责定义用户搜索的标准。当用户按下“搜索”,并使用选择的条件创建对象时,我试图循环遍历厕所数据以删除任何不适合的条目。问题是该函数没有返回正确的数组,当搜索特定条件时,该函数只返回一些匹配项,即使还有更多匹配项。

搜索对象代码(翻译成英文):

function SearchCriteria() {
    this.name = void 0;
    this.address = void 0;
    this.wheelchairAccesible = void 0;
    this.price = void 0;

    this.equals = function() {
        let matches = Object.values(toiletData.entries);

        Object.values(toiletData.entries).forEach(toilet => {
            Object.keys(this).forEach(key => {
                if ((this[key] !== undefined) && (typeof this[key] !== "function")) {
                    if (this[key] !== toilet[key]) {
                        matches.remove(toilet);
                    }
                }
            });
        });
        return matches;
    };
}

在 JSON 文件中,与变量关联的值是:

name = string, 
address = string, 
wheelchairAccesible = 1(yes) or 0(no),
price = int

【问题讨论】:

  • toiletData.entries 是一个对象数组还是只是一个对象还是什么?
  • toiletData.entries 是一个对象数组。将其打印到控制台返回:[{...}, {...},(更多){...}]
  • 我用需要的 JS 代码创建了一个小型 github 存储库github.com/haardes/stackArrayProblem
  • 问题中最好包含数据和预期结果。
  • 您希望搜索使用or 还是and?您希望搜索包含与每个搜索条件属性匹配的厕所,还是至少包含一个属性?

标签: javascript arrays function object this


【解决方案1】:

由于toiletData.entries 已经是一个数组,您不需要使用Object.values,因为它是多余的。另外,为什么要从数组的副本中删除元素,只需使用为您返回结果数组的filter

this.equals = function() {
    let searchKeys = Object.keys(this).filter(key =>                       // get a list of available search keys first (for the sake of both clarity and performance)
        this[key] !== undefined && typeof this[key] !== "function"
    );

    return toiletData.entries.filter(toilet =>                             // then for each toilet data entry
        searchKeys.every(key => this[key] == toilet[key])                  // filter only those that match all the search keys values
    );
};

注意:

this[key] == toilet[key] 中的=== 更改为==,这样"0" == 0 就是true,因为我认为搜索词始终是字符串,而toiletData.entries 中的数据可能是数字。您可能还想创建一个(更好的)函数来检查值的相等性(可能是小写字符串,转换为数字,...)。

【讨论】:

  • 解决了问题!
【解决方案2】:

与其循环遍历this 的每个属性,不如创建要匹配的属性,以及用户filtersome

var matchProps = ["name", "address", "wheelchairAccesible", "price"];
Object.values(toiletData.entries)
   .filter( toilet => !matchProps
     .some( key => this[key] != toilet[key] ) );

【讨论】:

    猜你喜欢
    • 2010-10-28
    • 1970-01-01
    • 2017-04-02
    • 2018-03-11
    • 1970-01-01
    • 2023-01-19
    • 2014-10-23
    • 2012-06-13
    相关资源
    最近更新 更多