使用jQuery搜索JSON对象 [英] Searching a JSON object with jQuery
本文介绍了使用jQuery搜索JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个需要查询的类似于JSON数组的javascript对象.我想知道是否有一种方法可以使用jQuery查找节点值,而无需遍历整个对象并依次测试每个节点是否匹配.例如,这是对象:
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."
}]
};
如果给定了ID,我又如何检索产品的名称和说明(同样,整个过程中都没有嵌套的each())?我已经尝试了jQuery的find()和属性选择器([id = a03]),但没有成功...我可以精确定位目标节点的唯一方法是使用索引位置(例如,
var x = $(Test.Species.Category[2].Product[1].attr('description'));
),但这不是目标.
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'));
推荐答案
var x = $(Test.Species.Category[0].Product[id='b02'].attr('description'));
var x = $(Test.Species.Category[0].Product[id='b02'].attr('name'));
这篇关于使用jQuery搜索JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文