0

Possible Duplicate:
Pick random property from a Javascript object

suppose I have a javascript object:

Config.UI.Area = {
        "uuid": {
            "_type": "string"
        },
        "frame": {
            "_type": "rect"
        },
        "zIndex": {
            "_type": "string"
        }
 }

then I want get each of the property's name,like "uuid","frame","zIndex" by using for loop:

var prop=config.ui.area;
var arr=new Array()
for(var i in prop){
    //do something with prop[i]?
    //arr.push(prop[i].....)?
}

I can not directly use prop[i],it would return me an object,how can I just get it's name?

Community
  • 1
  • 1
hh54188
  • 14,887
  • 32
  • 113
  • 184

4 Answers4

5

This would give you an array of property names:

for(var name in prop){
    //do something with prop[name]?
    arr.push(name);
}

It would also give you the names of 'native' properties of the Object object. To avoid that, use the hasOwnProperty method:

for(var name in prop){
    if (prop.hasOwnPropery(name) {
     arr.push(name);
    }
}
KooiInc
  • 119,216
  • 31
  • 141
  • 177
1

Below is how you iterate property and get corresponding value

var prop=config.ui.area;
var arr=new Array()
for(var i in prop){
    //do something with prop[i]?
    var propertyName = i;
    var propertyValue = prop[i];
}
Ramesh
  • 13,043
  • 3
  • 52
  • 88
0

prop (and Config.UI.Area) is an object ( not an array of object ). So you cannot do prop[i].

Try this,

   var obj = {
           "uuid": {
               "_type": "string"
           },
           "frame": {
               "_type": "rect"
           },
           "zIndex": {
               "_type": "string"
           }
    }

   var prop = obj;
   var arr=[];
   for(var i in prop){
       if(i.hasOwnProperty){
         arr.push(i);
       }
   }
   console.log(arr);
Jashwant
  • 28,410
  • 16
  • 70
  • 105
0

To get to the name of an object's property in a loop use:

for(var propertyName in myObject) {
  if(myObject.hasOwnProperty(propertyName) {
    console.log(propertyName); // will be uuid, frame or zIndex
  }
}

To get to properties of the sub objects, use

for(var propertyName in myObject) {
  if(myObject.hasOwnProperty(propertyName) {
    var subObject = myObject[propertyName];
    console.log(subObject._type);
           // will string or rect based on your sample code
  }
}

Using the hasOwnProperty in a loop through an object is a good idea as it will filter out properties of the object that are inherited via its prototype.

steveukx
  • 4,370
  • 19
  • 27