Skip to content

Instantly share code, notes, and snippets.

@garycourt
Forked from nicdaCosta/Grep.js
Created November 22, 2012 20:16
Show Gist options
  • Save garycourt/4132771 to your computer and use it in GitHub Desktop.
Save garycourt/4132771 to your computer and use it in GitHub Desktop.
Basic function that searches / filters any object or function and returns matched properties.
/*
Grep.js
Author : Nic da Costa ( @nic_daCosta ), Gary Court
Created : 2012/11/14
Version : 0.1.1
License : MIT, GPL licenses.
Overview:
Basic function that searches / filters any object or function and returns matched properties.
Main area of use would be for DevTools purposes, when needing to find a specific property but only part of
the property name is known.
Is now an inherited method on any Object / Function due to Object.prototype.
Thus can go ObjectName.Grep( 'SearchTerm' ).
eg: navigator.Grep( 'geo' );
var foo = function(){}; foo.Grep( 'proto' );
*Tested in Chrome Dev Tools*
*/
Object.prototype.Grep = function( strSearch , isRecursive ) {
// Checks if seach string is not empty/undefined
if ( !strSearch ) {
return this;
};
// Ignore case
strSearch = strSearch.toLowerCase();
// Used to prevent maxing out callstack for sub-lookups due to __proto__ == Object
isRecursive = isRecursive || false;
// Declare necessary local variables to hold necessary values
var objToIterate = this,
typeOfObject = typeof objToIterate,
objResult = {},
count = 0;
// if item that needs to be iterated over is an object or function, get all properties ( including non enumerable properties )
if ( typeOfObject === 'object' || typeOfObject === 'function' ) {
var objKeys = Object.getOwnPropertyNames( objToIterate );
// Loop through all the properties
for ( var x = 0, xl = objKeys.length; x < xl; ++x ) {
var item = objKeys[ x ];
// Check if key matches search string, if so add, if not, check if object and iterate through object's keys
if ( item.toLowerCase().indexOf( strSearch ) >= 0 ) {
objResult[ item ] = objToIterate[ item ];
++count;
}
else if ( typeof objToIterate[ item ] === 'object' && !isRecursive ){
objResult[ item ] = Grep.call( objToIterate[ item ] , strSearch , true );
++count;
}
} );
};
// checks if objResult is empty, if so, return empty string.
return count ? objResult : '';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment