portfolio | contact
May
Thursday the 14th

Recursively Search JSON Object

Thursday, 1:7 PM
I recently had a case where I needed to find a piece data in a rather large object. Since i couldn't be certain of its exact location within the object, i wrote a method to recurse through the object and return instances.

function findInObject ( srchObj, srchStr, resultSet ) {
var oKey, resultObj = {};
resultSet = resultSet || [];

for ( oKey in srchObj ){
if( srchObj.hasOwnProperty( oKey )) {
if ( oKey == srchStr || srchObj[ oKey ] == srchStr ){
resultObj[ oKey ] = srchObj[ oKey ];
resultSet.push( resultObj );

}
if ( srchObj[oKey] instanceof Object) {
findInObject( srchObj[oKey], srchStr, resultSet );
}
}
}
return resultSet;
}

◄ back