使用jQuery搜索JSON对象

时间:2010-12-11 01:57:23

标签: jquery

我有一个javascript对象,类似于JSON数组,我需要查询。我想知道是否有一种方法可以使用jQuery来查找节点值,而无需遍历整个对象并顺序测试每个节点以进行匹配。例如,这是对象:

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."
    }]
};

<小时/> 如果给定id,我怎么能检索产品的名称和描述(同样,没有嵌套each()通过整个事物)?我已经尝试过jQuery的find()和属性选择器([id = a03])但没有成功...我能精确定位节点的唯一方法是使用索引位置(例如var x = $(Test.Species.Category[2].Product[1].attr('description'));),但这不是目标。

我正在寻找更多这方面的内容,但这似乎不起作用:

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

1 个答案:

答案 0 :(得分:0)

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