Deep search, but without calls to recursive functions
Functional recursion has internal stack limitations and waste memory.
Additional features added
Recursive protection of objects in the form of the desired array; Of course, it does not use too much memory, since objects are stored only as links.
Returns true if the object itself matches the value. Otherwise, it will return '', which will be false.
Arrays use the notation of angle brackets.
The code
function globalSearch(startObject, value) { var stack = [[startObject,'']]; var searched = []; var found = false; var isArray = function(test) { return Object.prototype.toString.call( test ) === '[object Array]'; } while(stack.length) { var fromStack = stack.pop(); var obj = fromStack[0]; var address = fromStack[1]; if( typeof obj == typeof value && obj == value) { var found = address; break; }else if(typeof obj == "object" && searched.indexOf(obj) == -1){ if ( isArray(obj) ) { var prefix = '['; var postfix = ']'; }else { var prefix = '.'; var postfix = ''; } for( i in obj ) { stack.push( [ obj[i], address + prefix + i + postfix ] ); } searched.push(obj); } } return found == '' ? true : found; }
Problems
Without passing the intial variable name to the function, we cannot return the full variable name from the very beginning. I cannot come up with a solution, and I would be surprised if it were.
Variable names with spaces are valid as a key to the object, like other invalid variable names, it just means that the value must be addressed using angle brackets. There are several solutions that I can think of. Regex checks each variable name to make sure it is valid and uses the angle brackets if it is not. The main problem is that reg-ex is a page for a long time. As an alternative, we could only use angle brackets, but this is not entirely true for the original OP question.
Calling indexOf for a found array can be a bit heavy on very large objects, but I still cannot come up with an alternative.
<strong> Improvements
Besides clearing the code a bit, it would be nice if the function returned an array of matches. This also causes another problem: the returned array will not contain references to recursive objects. Perhaps the function may accept a result format configuration parameter.
thomas-peter
source share