1

I have an object with variable key names, which also contain objects. I would like to do a depth-first search (DFS) over the object.

An example object:

object = { "var1" : { 
                   "var2a" : {
                          "someKey" : someValue
                             },
                   "var2b" : {
                          "someKey" : someOtherValue
                            }}}

My attempt at a DFS is as follows (which will not work):

<div ng-repeat = "child in object">
     <div ng-repeat = "grandChild in child ">
          <td> {{grandChild.aKey}}</td>
     </div>
</div>

I have seen the approach of others in this previous question, however this will not work for me due to variable key names.

Additionally, the depth of the object is known.

If we use this code snippet to check what the result of child is:

<div ng-repeat = "child in object">
     <td> {{child}}</td>
     <div ng-repeat = "grandChild in child ">
          <td> {{grandChild.aKey}}</td>
     </div>
</div>

We get the first instance of child to be:

{"var2a" : {
           "someKey" : someValue
          }}

EDIT: Could it be possible to utilise this JavaScript DFS snippet that will output to console?

angular.forEach(object,function(child,value){
      angular.forEach(child,function(grandChild,value){
             console.log(grandChild.someKey)
      });
});
Community
  • 1
  • 1
eric
  • 301
  • 1
  • 4
  • 14

1 Answers1

1

So, it turns out that this is not actually possible using nested ng-Repeats. It must be done in JavaScript. This actually works in line with the 'Angular JS' mentality of keeping logic out of the HTML file.

Here is the DFS in JavaScript:

 angular.forEach(object,function(key,value){

                if (value!='$id'){ 
                           angular.forEach(key,function(keyChild,valueChild){

                                    console.log(valueChild)
                           }
                 });
  });

This will return "someKey" : someOtherValue and "someKey" : someOtherValue

eric
  • 301
  • 1
  • 4
  • 14