J. *_* Ed 70 jquery jquery-selectors
与brnwdrng的问题类似,我正在寻找一种搜索类似JSON的对象的方法.
假设我的对象的结构是这样的:
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."
}]
};
Run Code Online (Sandbox Code Playgroud)
我想得到一个id ="A"的对象.
我尝试过各种各样的东西,比如:
$(TestObj.find(":id='A'"))
Run Code Online (Sandbox Code Playgroud)
但似乎没什么用.
任何人都可以想到一种基于某些标准检索项目而不使用"每个"的方法吗?
Dav*_*ang 117
jQuery不适用于普通对象文字.您可以使用以下函数以类似的方式搜索所有'id'(或任何其他属性),无论其在对象中的深度如何:
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;
}
Run Code Online (Sandbox Code Playgroud)
使用如下:
getObjects(TestObj, 'id', 'A'); // Returns an array of matching objects
Run Code Online (Sandbox Code Playgroud)
dav*_*pcj 47
纯javascript解决方案更好,但jQuery方式是使用jQuery grep和/或map方法.可能没比使用$ .each好多少
jQuery.grep(TestObj, function(obj) {
return obj.id === "A";
});
Run Code Online (Sandbox Code Playgroud)
要么
jQuery.map(TestObj, function(obj) {
if(obj.id === "A")
return obj; // or return obj.name, whatever.
});
Run Code Online (Sandbox Code Playgroud)
返回匹配对象的数组,或者在map的情况下返回查找值的数组.可能只需使用那些就能做你想做的事.
但是在这个例子中你必须做一些递归,因为数据不是一个平面数组,我们接受任意结构,键和值,就像纯JavaScript解决方案一样.
function getObjects(obj, key, val) {
var retv = [];
if(jQuery.isPlainObject(obj))
{
if(obj[key] === val) // may want to add obj.hasOwnProperty(key) here.
retv.push(obj);
var objects = jQuery.grep(obj, function(elem) {
return (jQuery.isArray(elem) || jQuery.isPlainObject(elem));
});
retv.concat(jQuery.map(objects, function(elem){
return getObjects(elem, key, val);
}));
}
return retv;
}
Run Code Online (Sandbox Code Playgroud)
基本上与Box9的答案相同,但在有用的地方使用jQuery实用程序功能.
········
小智 5
这对我有用 [{"id":"data"},{"id":"data"}]
function getObjects(obj, key, val)
{
var newObj = false;
$.each(obj, function()
{
var testObject = this;
$.each(testObject, function(k,v)
{
//alert(k);
if(val == v && k == key)
{
newObj = testObject;
}
});
});
return newObj;
}
Run Code Online (Sandbox Code Playgroud)