Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use jQuery's find() on JSON object

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

I'd like to get an object with id="A".

I've tried all sort of stuff such as:

$(TestObj.find(":id='A'")) 

but nothing seems to work.

Can anyone think of a way of retrieving an item based on some criteria without using 'each'?

like image 349
J. Ed Avatar asked Feb 14 '11 12:02

J. Ed


People also ask

How can I access data from JSON object?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.

Can we search in JSON file?

Call a JS function when the user clicks the button. Read the file from disk on the server into a JS variable in the browser. Use lodash. js to get the url from the JS variable for the search term.

Can you nest objects in JSON?

Objects can be nested inside other objects. Each nested object must have a unique access path. The same field name can occur in nested objects in the same document.


1 Answers

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; } 

Use like so:

getObjects(TestObj, 'id', 'A'); // Returns an array of matching objects 
like image 186
David Tang Avatar answered Oct 04 '22 13:10

David Tang