I would like to point out the possibility of iterating over an object and find the name of the parent of a property recursively. With it, the test function will look like this:
var test = function(rootobj,propname,rootObjName) {
Where findParents :
function findParents(obj,key,rootName){ var parentName = rootname || 'ROOT', result = []; function iterate(obj, doIndent){ var parentPrevName = '' for (var property in obj) { if (obj.hasOwnProperty(property)){ if (obj[property].constructor === Object) { parentPrevName = parentName; parentName = property; iterate(obj[property]); parentName = parentPrevName; } if (key === property) { result.push('Found parent for key [' +key+' (value: '+obj[property] +')] => '+parentName); } } } } iterate(obj); return result; }
The problem, of course, is that the property does not have to be unique. How in:
var a = { 'light': 'good', 'dark' : { 'black': 'bad', 'gray' : 'not so bad' 'yellow' : { 'dark': 'will do', //<=there 'dark' again! 'light':'never use' } } }
Well, maybe it can be used. You can find a demo of the findParents function at http://jsfiddle.net/KooiInc/Kj2b9/
Kooiinc
source share