0

I want to loop through an array of objects, and for each object console.log its attributes. Let's say we don't know what the attributes are.

The code looks like this.

qData = [object ,object, object, object, object];
for(props in qData){
  //display all of props object attributes
}

How can I output their attributes?

mjk
  • 2,443
  • 4
  • 33
  • 33
user1551482
  • 529
  • 4
  • 9
  • 15
  • possible duplicate of [How to get an object's properties in JavaScript / jQuery?](http://stackoverflow.com/questions/4079274/how-to-get-an-objects-properties-in-javascript-jquery) – Felix Kling Aug 20 '12 at 17:12

1 Answers1

2

You can do that like this:

var qData = [object, object, object, object, object];
for (var i = 0; i < qData.length; i++) {
    var obj = qData[i];
    for (var prop in obj) {
        console.log(prop + "=" + obj[prop]);
    }
}

You first iterate through the array and then for each array element, you iterate through the properties. Keep in mind that you iterate array elements with for (var i = 0; i < array.length; i++) and you iterate properties with for (props in array).


If you only want direct properties of the object (and not any enumerable properties of parent objects), you would use this:

var qData = [object, object, object, object, object];
for (var i = 0; i < qData.length; i++) {
    var obj = qData[i];
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            console.log(prop + "=" + obj[prop]);
        }
    }
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979