I have a object graph with the following structure:
topic
- obj #1
- obj #2
--- attr #2 name
--- attr #2 elements
------obj element #1
---------attr element #1 name
---------attr element #1 comment
---------attr element #1 etc.
------obj element #2
--- attr #2 etc.
- obj #3
It consists of objects and arrays of objects. I need to get every Element but the graph has an unknown number of levels. So, in order to go through all elements, a recursive loop is needed (I guess?).
Now I have two different tasks:
1.) First the easier one: I want to search for an attribute name (value of an object) and not return true (found) or false, but return the object, in which I found this value. (assume there is just one instance with the exact name).
2.) At the last level objects (e.g. 'obj element #1' with its attributes 'name', 'comment' and 'etc.') I want to call another method and pass as a parameter the complete path there: In this example one of the paths would be:
Topic -> obj #2 -> obj element #1. And the next one (for the next call of the function):
Topic -> obj #2 -> obj element #2.
So it will need an array to store the 'path' over the recursion. This array also needs to be altered, e.g. when going to the next element, it is necessary to delete the last element of the path and add the new element (#2). Same, when going coming back from recursion.
Here is what I tried (it is obviously not right and maybe some returns are useless/too much). Regarding 1) :
function findIdentifier (obj, identifier){
var el=null;
if(typeof obj === 'object'){
if (!Array.isArray(obj)){
for(var key in obj){
if (obj.hasOwnProperty(key)) {
if (key.indexOf(identifier) !== -1 || obj[key] === identifier){
//found right object
el = obj[key];
return el;
}
else el = findIdentifier(obj[Object.keys(obj)[0]],identifier);
}
}
return el;
}
else{
for(var i=0; i<obj.length; i++){
if (obj[i].indexOf(identifier) !== -1 && obj.length>1){
el = obj[i];
return el;
}
else el = findIdentifier(obj[0],identifier);
}
return el;
}
}
return el;
}
I hope you guys understand what I mean. I'm grateful for every answer!