Searching through a JSON Array

I am attempting to search through a JSON array using JQuery, however, I keep getting this error…Uncaught TypeError: val.ID.search is not a function.
The Json file is called “smallData.json” and the contents are below along with javascript and jquery code.

[
 {
   "ID": 1,
   "Station": "Carmichael Rd.",
   "Address": "54 Myers Rd.",
   "Monthly_CStore_Sales": "120,000",
   "Operator": "Michael Sears",
   "Top_SKU": "Hotdogs"
 },
 {
   "ID": 2,
   "Station": "Baillou Hill",
   "Address": "564 Jackson Ave.",
   "Monthly_CStore_Sales": "89000",
   "Operator": "Sarah Pikes",
   "Top_SKU": "Patties"
 },
 {
   "ID": 3,
   "Station": "Oakesfield",
   "Address": "42 Peterson St.",
   "Monthly_CStore_Sales": "150000",
   "Operator": "Yolanda Gray",
   "Top_SKU": "Chicken"
 ] 
</head>
    <body>
     <p><br></br></p>
      <div class="container">
      <input type="search" class="form-control" id="search"></div></br>
      <table class="table table-striped table-bordered table-hover"></table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Station</th>
            <th>Address</th>
            <th>Monthly_CStore_Sales</th>
            <th>Operator</th>
            <th>Top_SKU</th>
          </tr>
        </thead>
        <tbody>
        </tbody>
      </table>


<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    
  
  
  <script>
    $('#search').keydown(function(){
      $.getJSON("smallData.json",function(data){
        var search = $('#search').val();
        var regex = new RegExp(search,'i');
        var output;
        $.each(data, function(key, val){
           if((val.ID.search(regex) != -1)  || (val.Station.search(regex) != -1)){
            output += "<tr>";
            output += "<td id='"+key+"'>"+val.ID+"</td>";
            output += "<td id='"+key+"'>"+val.Station+"</td>";
            output += "<td id='"+key+"'>"+val.Address+"</td>";
            output += "<td id='"+key+"'>"+val.Monthly_CStore_Sales+"</td>";
            output += "<td id='"+key+"'>"+val.Top_SKU+"</td>";
            output += "</tr>";
          }
        });
        $('tbody').html(output);
        });
      })
            
  </script>


</body>
</html> 

val.ID is number

Hi @martt70, as @igor_g pointed out that value is a number, and numbers don’t have a search() method. However you can convert it to a string like this

val.ID.toString().search(regex)

or implicitly by concatenating it with an empty string

(val.ID + '').search(regex)

or using ES6 syntax

`${val.ID}`.search(regex)

BTW I’d suggest to use indexOf(search) rather than constructing a regular expression as you’d have to escape all the special characters otherwise.

Or… just filter your data array, instead of doing all the math inside the loop and invoking search on every iteration…

(Code not IE friendly. Because i’m lazy.)

   var data = data.filter((val) => val.ID != -1 || val.Station != -1);

(the whole… string-to-int thing is redundant in JS because it implicitly converts str to int to do the comparison. “-1” == -1 is true.)

EDIT: Or i could read the post properly. Sigh.
var data = data.filter((val) => val.ID == search || val.Station.includes(search));

[off-topic]

I am aware the question requires jQuery and JavaScript but curious to know if using Php is an acceptable alternative…

https://www.php.net/manual/en/function.json-decode.php

Server side processing would be far quicker to create a PHP array. The created PHP array result could be converted to a string of table PHP $aRows and inserted into the table:

  <table class="table table-striped table-bordered table-hover"></table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Station</th>
            <th>Address</th>
            <th>Monthly_CStore_Sales</th>
            <th>Operator</th>
            <th>Top_SKU</th>
          </tr>
        </thead>
          <?= $aRows ?>
        <tbody>
        </tbody>
      </table>

[/off-topic]

Edit:
Slightly reworded to try and make easier to understand.

Thank you…I made the changes and the error went away, however, I still can’t get the search to work…nothing happens…can you please tell me where perhaps, I am going wrong?

I want to stick with the browser for this exercise…I’m working server side soon and may need your help later John…thanks…

1 Like

I am no longer, getting an error but I can’t seen to get it to work…nothing happens…Can you please help me?

Hi…I made the changes and the error has been removed but I can’t seem to get the code to work…can you please help?

Your JSON is not well formed, so you’re probably not getting the kind of response you’re expecting. But as you’re not going to do any server side processing as @John_Betong suggests, sending a request on every key up event is not necessary anyway; you might just fetch the data once initially and then populate the table according to the user input.

BTW your generated markup is not valid either as you’re assigning the same ID to multiple elements – just set it to the tr instead of each td element.

1 Like

I put the JSON you show into Online JSON Viewer and it complains about Monthly_CStore_Sales and Top_SKU. There are very many other online JSON viewers and formatters and it can really help to use them.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.