jqueryjson

Searching JSON file properly


I am having a hard time searching a JSON document with JS/jQuery. Here is my JSON file.

I have two select lists in my application, one that selects one of the top-level arrays (150, 300, 600, 900 etc), and one that selects an a value within one of the objects (diameter). I would like to display all matches. I've tried a couple of things already, but I can seem to select the proper array to search in - I can only get them by number (0, 1, 2 etc) not by name (150, 300 etc).

Here is my current function:

 $("#btnBeregn").click(function(){  
            //$("#loader").fadeIn(200);
            $("#resultsTable").html("");
            var currDiameter = $("#ddlDiameter option:selected").val();
            var currDim = $("#ddlRorklasse option:selected").val();
            
            $.getJSON("calctable.json", function(data) {
            
                $.each(data, function(i, v) {
                        $.each(v, function(x,y) {
                        
                            if(y.bolts == "32"){
                                console.log('16 boolts');
                            }
                        
                        });
                });
            
            
            });
            
        
        
    });

Solution

  • $.each iterates over arrays, not objects, and when JSON is parsed, the output is an object.

    The way to iterate over JavaScript objects is:

    for (var key in object) {
      if (object.hasOwnProperty(key)) {
        // key is the key, object[key] is the value
      }
    }
    

    For more information on iterating over objects, see How to Loop through plain JavaScript object with objects as members? .

    Edit: In your case, to get a particular item that matches a certain property, you can do something like this:

    $.each(data["150"], function(i, item) {
        if (item.diameter == "0,5 / 15mm") {
            console.log(item);
        }
    });
    

    Edit #2: I looked up $.each, and it looks like I was wrong about it. It can be used to iterate over both arrays and objects (http://api.jquery.com/jQuery.each/). That said, in your case, given how the data is structured, only one $.each is needed, as I've shown above.