Getting the object's property name

Olical picture Olical · Nov 23, 2010 · Viewed 327.3k times · Source

I was wondering if there was any way in JavaScript to loop through an object like so.

for(var i in myObject) {
    // ...
}

But get the name of each property like this.

for(var i in myObject) {
    separateObj[myObject[i].name] = myObject[i];
}

I can't seem to find anything like it on Google. They say to pass the names of the variables with them but this is not an option for what I am trying to achieve.

Thanks for any help you can offer.

Answer

Josiah Ruddell picture Josiah Ruddell · Nov 23, 2010

i is the name.

for(var name in obj) {
    alert(name);
    var value = obj[name];
    alert(value);
}

So you could do:

seperateObj[i] = myObject[i];