Rouge
Rouge

Reputation: 4239

How to get the properties from object

I am trying to handle a callback data from ajax and having a problem looping the data.

I have

data.prototype.handleReturnData = function(data) {

}

data is an object which contains 4 objects. Each object has a test and test2 property.

How do I get those properties?

Thanks a lot!

Upvotes: 0

Views: 73

Answers (4)

ars265
ars265

Reputation: 1987

I would suggest:

Object.getOwnPropertyNames(yourobject);

This will get all the property names which you can then use to cycle through or pick your property.

Upvotes: 1

tuff
tuff

Reputation: 5163

You can use a for-in loop:

for (var prop in data) {
    if( data.hasOwnProperty(prop)) {
        // 'prop' refers to the property name
        // do something with data[prop] or data[prop].test
    }
}

The purpose of the hasOwnProperty check is to exclude inherited properties, which you probably aren't interested in. Some documentation here: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/for...in

Upvotes: 1

Lkrups
Lkrups

Reputation: 1344

Try accessing your values with data[0]['test'].

Upvotes: 2

Konstantin Dinev
Konstantin Dinev

Reputation: 34915

Try this:

for (var i = 0; i < data.length; i++) {
    alert(data[i].test);
    alert(data[i].test2);
}

Upvotes: 0

Related Questions