I would like to point you to the possibility to iterate through an object and recursively find the name of the parent of some property. With it your test
function would look like:
var test = function(rootobj,propname,rootObjName) {
// do smth with object AS rootobj[propname]
var objparents = findParents(rootobj,propname,rootObjName);
}
test(a,'dark','a');
Where findParents
is:
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 a property wouldn't have to be unique. As in:
var a =
{
'light': 'good',
'dark' : {
'black': 'bad',
'gray' : 'not so bad'
'yellow' : {
'dark': 'will do', //<=there's 'dark' again!
'light':'never use'
}
}
}
Well, may be it's usable. You can find a demo of the findParents function in http://jsfiddle.net/KooiInc/Kj2b9/