Search code examples
javascriptobject-literalfor-in-loop

Is there a way to access an object literal's name?


I have an object:

var Top = {
    'A':{},
    'b':{
        '1':'someText',
        '2':'someMoreText'},
    'C':{
        '3':'evenMoreText',
        '4':'thisIsGettingRedundant'},
    'D':'thisOneIsDifferent'}

I am looking for a way to access the name of my objects, like Top[b].objectName would return 'Top' as a string, I am doing this inside some nested for...in loops, like this:

for(thing in Top){
    for(piece in Top[thing]){
        console.log('Grabbing ' + Top[thing][piece] + ' from ' + MY_OBJECT_NAME_THAT_SHOULD_BE_TOP);
    }
}

I suppose I could add a tag to each object for their name (IE. changing A from {} to 'Top'), but that seems redundant to me.

-Edit:

is there a way to log my second level object names IE. A, B, C? as they SHOULD be logged as data and not code


Solution

  • const Top = {
      'A': {},
      'b': {
        '1': 'someText',
        '2': 'someMoreText'
      },
      'C': {
        '3': 'evenMoreText',
        '4': 'thisIsGettingRedundant'
      },
      'D': 'thisOneIsDifferent'
    };
    

    To achieve this, use a for-in-loop to iterate over all the keys @ the top level. If the key points to an object and is not equal to null (defined as an object in JavaScript), perform another for-in-loop to log each item into the console. Should the top level key point to an empty object, log empty curvy brackets to the console. On the other hand, if the top-level key point to a non-object, log that to the console.

    for(let key in Top) {
      if(typeof Top[key] === 'object' && Top[key] !== null) {
        for(let item in Top[key]) {
          console.log(`Grabbing ${Top[key][item]} from '${item}' within '${key}' in Top.`);
        }
    
        if(Object.keys(Top[key]).length === 0) {
          console.log(`Grabbing {} from '${key}' in Top.`);
        }
      } else {
        console.log(`Grabbing ${Top[key]} from '${key}' in Top.`);
      }
    }