2

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

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

Parse the 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);

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

---UPDATE---

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

1 Answer 1

6

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".

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the quick answer, I tried something like this earlier to no avail. When using your code I get: Uncaught TypeError: Cannot call method 'toLowerCase' of null
Ensure your array elements are all strings. Also, clearly you have at least one element that doesn't exist in the array. Can we get a sample piece of json?
@Visiophobia, it appears that either val or el[type] is null in at least one case. regex.exec returns null if it doesn't match anything, so that's likely your problem.
I've added an example, and yes there are cases of 'null' (but there won't be in the final version). Will the method stated above work at that point?
I tried if (el[type]!=null && val!=null) { return el[type].toLowerCase() === val.toLowerCase(); } and it worked! thanks guys! Now to try and figure out partial searches :S

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.