-3

Simple question...or so I think...

Is there a way to get the name of the object your looping through inside the each statement?

I need the name inside a loop so I can attach some elements to it on the page. This seems like the only way I can do so.

My full objects looks like this

 BO:{C: 1}
 CA1:{}
 CRA:{}
 DE:{RT: 14}
 TX:{}

These are smaller objects within a larger one that I am looping through.

and my for loop looks like this

$.each(v, function (o, p) {
  console.log(p)
  //looking the get the 'BO' or 'DE' inside here so I can do an append to the element on the page
});

When looping through this if I console out o, I get the variable C and when I console out the p I get the variable 1. As you can see below. I need to get the name of BO so need to go up and grab that variable so I can properly name my id.

I do not have access to outside variables within the for loop.

enter image description here

any help appreciated!

zazvorniki
  • 3,512
  • 21
  • 74
  • 122

1 Answers1

0

You can simply iterate through the properties of the object if you need just the name of the property, not its value :

var obj = {
  'BO': {
    'C': 1
  },
  'CA1': {},
  'CRA': {},
  'DE': {
    'RT': 14
  },
  'TX': {},
}

for( var s in obj ) {
  console.log(s);
}

Here's the working example : https://jsfiddle.net/yyLz0ae6/

DinoMyte
  • 8,737
  • 1
  • 19
  • 26