Created
March 25, 2013 14:03
-
-
Save blowsie/5237314 to your computer and use it in GitHub Desktop.
Returns JSON OBJ and its parents based on a data set, key and match.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//#region function recursiveFind | |
function recursiveFind(data, key, childKey, match, result) { | |
///<summary>Returns JSON 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 data object you want to find within</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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment