1

I have a javascript object, akin to a JSON array, that I need to query. I wanted to know if there is a way to use jQuery to find node values without iterating through the entire object and sequentially testing every node for a match. For example, here is the object:

Test = {};

Test.Species = {
    "Category": [{
        "Product": [{
            "id": "a01",
            "name": "Pine",
            "description": "Short description of pine."
        },
        {
            "id": "a02",
            "name": "Birch",
            "description": "Short description of birch."
        },
        {
            "id": "a03",
            "name": "Poplar",
            "description": "Short description of poplar."
        }],
        "id": "A",
        "title": "Cheap",
        "description": "Short description of category A."
    },
    {
        "Product": [{
            "id": "b01",
            "name": "Maple",
            "description": "Short description of maple."
        },
        {
            "id": "b02",
            "name": "Oak",
            "description": "Short description of oak."
        },
        {
            "id": "b03",
            "name": "Bamboo",
            "description": "Short description of bamboo."
        }],
        "id": "B",
        "title": "Moderate",
        "description": "Short description of category B."
    },
    {
        "Product": [{
            "id": "c01",
            "name": "Ebony",
            "description": "Short description of ebony."
        },
        {
            "id": "c02",
            "name": "Rosewood",
            "description": "Short description of rosewood."
        },
        {
            "id": "c03",
            "name": "Bubinga",
            "description": "Short description of bubinga."
        }],
        "id": "C",
        "title": "Expensive",
        "description": "Short description of category C."
    }]
};


How could I retrieve the name and description of a product if given the id (again, without a nested each() through the whole thing)? I've tried jQuery's find() and attribute selectors ([id=a03]) with no success... The only way I can precisely target nodes is using the index position (e.g., var x = $(Test.Species.Category[2].Product[1].attr('description'));), but that's not the goal.

I'm looking for something more along these lines, but this doesn't seem to work:

var x = $(Test.Species.Category[id='B'].Product[id='b02'].attr('description'));

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385
brnwdrng
  • 521
  • 2
  • 8
  • 18
  • Javascript has a function filter() which might help with that but it does not work in IE7 or lower. – Pieter Dec 11 '10 at 02:19

1 Answers1

0
var x = $(Test.Species.Category[0].Product[id='b02'].attr('description'));
var x = $(Test.Species.Category[0].Product[id='b02'].attr('name'));
mariana soffer
  • 1,853
  • 12
  • 17