与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." }] };
我想获得一个id =“ A”的对象。
我已经尝试过各种方法,例如:
$(TestObj.find(":id='A'"))
但似乎没有任何效果。
任何人都可以想到一种无需使用“每个”即可根据某些条件检索项目的方法吗?
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; }
像这样使用:
getObjects(TestObj, 'id', 'A'); // Returns an array of matching objects