本文介绍了在JSON对象上使用jQuery的find()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
类似于 brnwdrng的问题,我正在寻找一种方法搜索类似JSON的对象.
假设我对象的结构是这样的:
Similar to brnwdrng's question, I'm looking for a way to search through a JSON-like object.
supposing my object's structure is like so:
TestObj = {
"Categories": [{
"Products": [{
"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."
}]
};
我想获得一个id ="A"的对象.
I'd like to get an object with id="A".
我尝试了各种东西,例如:
I've tried all sort of stuff such as:
$(TestObj.find(":id='A'"))
但似乎没有任何作用.
任何人都可以想到一种无需使用每个"就可以根据某些条件检索项目的方法吗?
Can anyone think of a way of retrieving an item based on some criteria without using 'each'?
推荐答案
jQuery不适用于普通对象文字.您可以类似的方式使用以下函数来搜索所有"id"(或任何其他属性),而不管其在对象中的深度如何:
jQuery doesn't work on plain object literals. You can use the below function in a similar way to search all 'id's (or any other property), regardless of its depth in the object:
function getObjects(obj, key, val) {
var objects = [];
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
if (typeof obj[i] == 'object') {
objects = objects.concat(getObjects(obj[i], key, val));
} else if (i == key && obj[key] == val) {
objects.push(obj);
}
}
return objects;
}
使用方式如下:
getObjects(TestObj, 'id', 'A'); // Returns an array of matching objects
这篇关于在JSON对象上使用jQuery的find()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!