0

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

                        });
                });


            });



    });

1 Answers1

0

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

Community
  • 1
  • 1
BadgerPriest
  • 723
  • 5
  • 11
  • Hi! Thanks for your reply! Well that changes a lot in the way I think of things. Still having a hard time though, but Iam getting there. Is there any easy solution to get out for example the object under the 150 object that has a diameter of 0,5 / 15mm. Do I need two for loops for that? Again, thanks a lot. This helped me much. – Steffen Martinsen Jul 29 '13 at 11:46
  • Thanks a lot! It worked like a charm, and now I understand why! – Steffen Martinsen Jul 31 '13 at 22:35