I wrote the following code as a way of plucking data from a n-depth JavaScript object. It works a charm and even appends the parents of the the found item.
I was just wondering if you guys had any ideas on making it better.
//#region function recursiveFind
function recursiveFind(data, key, childKey, match, result) {
///<summary>Returns JS obj and its parents based on a data set, key and match.</summary>
///<param name="data" type="Object" optional="false">the data object you want to find within</param>
///<param name="key" type="String" optional="false">the key for the data you want to match against eg. 'id' will look for data.id</param>
///<param name="childKey" type="String" optional="false">the data object you want to find within</param>
///<param name="match" type="Any" optional="false">the value you wish to search for</param>
///<returns type="Object">returns the found result</returns>
var parents = [];
var depth = 0;
var recurse = function (data, key, childKey, match, result) {
// Build Parents
depth++;
// Check this Object
if (data[key] === match) {
result = data;
}
else if (depth === 1) {
parents.push(data);
}
// If not found check children
if (result === undefined) {
if (data[childKey]) {
$.each(data[childKey], function (k, v) {
if (v[key] === match) {
result = v;
return false;
} else {
result = recurse(v, key, childKey, match, result);
if (result) {
parents.push(v);
return false;
}
}
});
}
}
// Set parents object into the result
if (result) {
result.parents = $.extend([], parents);
}
// Clean up parents object
depth--;
if (depth === 0) {
parents.length = 0;
}
return result;
};
return recurse(data, key, childKey, match, result);
}
//#endregion