views:

72

answers:

3

My JSON object is constructed like this:

var Source =
{
    Object: [ //Array
        {Title: 'Test', Type: 'Pet', Category: 'Cat', Description: 'Fluffy', Count: 2 }
    ]
};

I was able to figure out how to properly add to the 'Object' array, but I can't seem to figure out the jQuery syntax to query the object based on the property list (Title, Type, Category, etc).

I put some test code into a click event and normally check the length of the Source.Object (Test data results in 2 objects) to confirm that there is data to work with (It's populated through an ajax call).

function clickTest(category, type) {
    $(Source).find('Object[Category=\"' + category + '\"]').each(function() {
        alert($(this).attr('Category')); //doesn't work
    });
}

What is the right way to query a JSON object like this?

+3  A: 

JSON is native to JavaScript and can be cycled through without the use of libraries (jQuery). The [] represent arrays, and {} represent objects, therefore:

var obj = Source.Object;
for (var i = 0, len = obj.length; i < len; i++) {
    if (obj[i].Category == category)
        alert(obj[i].Category + ' ' + obj[i].Title);
}

And that's faster, too! Good stuff.

Alexander Gyoshev
I'd always assumed that jQuery would be faster then building a javascript loop to make these checks.
C Bauer
@C Bauer: jQuery would be shorter. Pure JavaScript will be faster (since the closures call variables from other scope, etc.) After all, jQuery is written in JavaScript -- calling it won't always beat a custom solution.
Alexander Gyoshev
+4  A: 

The source is a JSON object, not a HTML DOM. Therefore, you must use the jQuery utility functions for arrays:

$.grep( Source.Object, function(e) { return e.Category == category } ).each(...)
Aaron Digulla
"must" sounds rather extreme, no? :)
Alexander Gyoshev
+1 - the rare (mostly) proper use of `$.grep()`, the `.each()` after will blow up though, it should be wrapped in a `$.each(...)`, since `.grep()` returns an array.
Nick Craver
I would correct: "you _can_ use the jQuery utility functions" - they're not necessary as that's just plain JavaScript.
Tatu Ulmanen
nice, i didn't know $.grep(object, function) but it's good to know :)
samy
+1  A: 

JSon is a way to transcribe a javascript object in a string format and transmit it on the wire. One nice thing about the format is that it's directly readable by javascript, so your Source object is already ready to be processed.

function processSource(source, category)
{
    var counter = 0;
    for (counter = 0; counter < source.Object.length; counter += 1)
    {
        if (category === source.Object[counter].category) {
           // do something
        }
    }
}
samy