如何使用javascript使用不区分大小写的搜索从JSON返回结果? [英] How to return a result from JSON with case insensitive search using javascript?

查看:591
本文介绍了如何使用javascript使用不区分大小写的搜索从JSON返回结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的JSON包含每个具有多个值(名称,制造商等)的产品"

My JSON contains 'products' that each have multiple values (name, manufacturer etc.)

我有以下代码,该代码可让我根据从查询字符串获取的搜索结果从JSON中提取产品".它可以正常工作,但前提是搜索条目的格式必须完全符合其在字符串中的书写方式.

I have the following code that allows me to pull 'products' from my JSON based on a search result acquired from a query string. It works fine, but only if the search entry is formatted exactly how it is written in the string.

如何允许不区分大小写的搜索产生期望的结果(最好是部分搜索)?

How can I allow case insensitive searches yield the desired result (and ideally, partial searches)?

我相信正则表达式是可行的方法,但是我已经用尽了我的知识,而且似乎无法用它做任何事情.

I believe that regular expressions are the way to go, but I've exhausted my knowledge and can't seem to get anywhere with it.

我试图摆弄小提琴,但无法正常进行演示,因此,我尝试合并代码并对其进行注释以使其更加清晰.任何帮助将不胜感激:)

I tried to put together a fiddle but couldn't get a proper demo working, so instead I've tried to consolidate the code and comment it for clarity. Any help would be greatly appreciated :)

解析JSON:

var prodobjects = JSON.parse(prods);

根据特定价值获取产品的代码:

Code to get products based on specific value:

function getData(array, type, val) {
  return array.filter(function (el) { 
    return el[type] === val;
  });
}

用于检索查询字符串的代码:

Code to retrieve query string:

function gup( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
var regexS = "[\\?&]"+name+"=([^&#]*)";  
var regex = new RegExp( regexS );  
var results = regex.exec( window.location.href ); 
 if( results == null )    return "";  
else    return results[1];}

我要使用的查询字符串部分:

Section of query string I want to use:

var prodresult = gup( 'search' );   

删除加号并替换为空格:

Remove plusses and replace with spaces:

var removeplus = prodresult.replace(/\+/g, ' ');

编译产品名称与搜索"查询相匹配的产品名称:

Compile list of products with their 'Prodname' matching the 'search' query:

var searchname = getData(prodobjects.products, 'Prodname', removeplus);

根据要求,这里是JSON的示例.它仍在开发中,因此当前正在计算null值等(通过api接收).这只是产品之一,但是实际的字符串包含许多相同的格式(但在产品"中):

And as requested here is a sample of the JSON. It's still in development so the null values etc. are currently being worked out (it's received through an api). This is just one of the products, but the actual string contains many in the same format (but within "products"):

var prods = JSON.stringify({"products": [
    {
        "Prodname": null,
        "Oem": "Example OEM",
        "Snippet": "Example Snippet",
        "Linkto": "www.linkhere.com",
        "Imagesource": "image.png",
        "Category": "Category",
        "Tagline": "Tagline goes here",
        "Longdescription": [
            {
                "Paragraph": "<p>First description of the paragraph</p>"
            },
            null,
            null,
            null
        ],
        "Features": null,
        "Company": false,
        "Subscribed": false,
        "Tariffs": [
            {
                "Tarname": "Tariff one",
                "Tarpaysched": "Monthly per User",
                "Tarcost": "£1"
            },
            null,
            null,
            null,
            null,
            null
        ],
        "Extratariffs": null
    }
]
});

-更新---

我设法通过以下方式使其能够支持部分搜索和不区分大小写:

I managed to get it working to support partial searches and case insensitivity with the following:

function getData(array, type, val) {
  return array.filter(function (el) {
      if (el[type]!=null && val!=null) {
          var seeker = val.toLowerCase();
          var rooted = el[type].toLowerCase();
          var boxfresh = rooted.indexOf(seeker);
          if (boxfresh!=-1) {
              return rooted
          }
      }
  });
}

推荐答案

您可以将两个字符串转换为小写(或大写),以使比较不区分大小写.

You can convert two strings to lowercase (or uppercase) to make the comparison case-insensitive.

function getData(array, type, val) {
  return array.filter(function (el) { 
    return el[type].toLowerCase() === val.toLowerCase();
  });
}

为了更好地进行搜索,您可能需要研究模糊比较,即搜索数据以确定可能的拼写错误和近似的字符串匹配."

For better searching, you might want to look into fuzzy comparison, which is "a search against data to determine likely mispellings and approximate string matching".

这篇关于如何使用javascript使用不区分大小写的搜索从JSON返回结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆