tetris11
tetris11

Reputation: 817

Javascript: Grabbing the first element from a nested map

For a two level map I'm using:

var first = function(){
    for(var one in map)
        for(var two in map[one])
            return map[one][two];
    }

is there an easier way? Possibly something along the lines of

map.first()

?

Upvotes: 0

Views: 95

Answers (1)

peoro
peoro

Reputation: 26060

I'm not really getting what you're trying to do, but the easiest way to handle nested structures with an unknown depth is recursion:

var getWhatever = function(obj)
{
  if( isWhatever(obj) ) {
    return obj;
  }
  for( var field in obj ) {
    return getWhatever( obj[field] );
  }
};

Upvotes: 2

Related Questions