Search code examples
javascriptobject-literal

How Can I Check a Object Literal's Name in JavaScript?


Here I got a object literal which looks like this one below:

var assets = {
  images: {
    'sky': 'assets/sky.png',
    'platform': 'assets/platform.png'
  },
  spritesheets: {
    'dude': 'assets/dude.png'
  }
}

And my objective is to create a function which can invoke different functions depends on the type of these assets.

I was thinking of this kind of solution:

function preload() {
  for (var asset in assets) {
    switch ( /* check the asset's type */ ) {
      case 'images':
        // do something
        break;
      case 'spritesheets':
        // do something
        break;
    }
  }
}

How should I implement it?

Sorry for my poor use of English, since I'm not a native speaker. ;D


Solution

  • Javascript's for...in feature loops over the properties (or keys) of an object, not the values. So you could do this:

    function preload() {
      for (var asset in assets) {
        switch (asset) {
          case 'images':
            for (var image in assets[asset]) {
              // assets[asset][image] will be an image url
            }
            break;
          case 'spritesheets':
            for (var spritesheet in assets[asset]) {
              // assets[asset][spritesheet] will be an spritesheet url
            }
            break;
        }
      }
    }