[javascript] How to iterate through property names of Javascript object?

I would like to get the property names from a Javascript object to build a table dynamically. Example:

var obj = {'fname': 'joe', 'lname': 'smith', 'number': '34'};

for (var i = 0; i < obj.properties.length; i++) {
  alert(' name=' + obj.properties[i].name + ' value=' + obj.properties[i].value);
}

would alert:

name=fname value=joe

name=lname value=smith

name=number value=34

Then I could build a table using object like this:

var obj = { 'players': [ 
     { 'fname': 'joe', 'lname': 'smith', 'number': '34'} , 
     { 'fname': 'jim', 'lname': 'Hoff', 'number': '12'} , 
     { 'fname': 'jack', 'lname': 'jones', 'number': '84'}   
] };    

to produce:

| fname |  lname |  number |
|-------|--------|---------|
| joe   | smith  |      34 |
| jim   | Hoff   |      12 |
| jack  | jones  |      84 |

UPDATE

Thanks to the answer, I have produced a table from the Javascript objects using the property names from the first object in the list for the headers:

    function renderData() {
        var obj = { 'players': [
            { 'fname': 'joe', 'lname': 'smith', 'number': '34' },
            { 'fname': 'jim', 'lname': 'jones', 'number': '12' },
            { 'fname': 'jack', 'lname': 'Hoff', 'number': '84' } 
            ] };

        var cols = GetHeaders(obj); 

        $('#Output').html(CreateTable(obj, cols));
    }

    function CreateTable(obj, cols) {
        var table = $('<table></table>');
        var th = $('<tr></tr>');
        for (var i = 0; i < cols.length; i++) {
            th.append('<th>' + cols[i] + '</th>');
        }
        table.append(th);

        for (var j = 0; j < obj.players.length; j++) {
            var player = obj.players[j];
            var tr = $('<tr></tr>');
            for (var k = 0; k < cols.length; k++) {
                var columnName = cols[k];
                tr.append('<td>' + player[columnName] + '</td>');
            }
            table.append(tr);
        }
        return table;
    }

    function GetHeaders(obj) {
        var cols = new Array();
        var p = obj.players[0];
        for (var key in p) {
            //alert(' name=' + key + ' value=' + p[key]);
            cols.push(key);
        }
        return cols;
    }

This question is related to javascript loops object

The answer is


In JavaScript 1.8.5, Object.getOwnPropertyNames returns an array of all properties found directly upon a given object.

Object.getOwnPropertyNames ( obj )

and another method Object.keys, which returns an array containing the names of all of the given object's own enumerable properties.

Object.keys( obj )

I used forEach to list values and keys in obj, same as for (var key in obj) ..

Object.keys(obj).forEach(function (key) {
      console.log( key , obj[key] );
});

This all are new features in ECMAScript , the mothods getOwnPropertyNames, keys won't supports old browser's.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to loops

How to increment a letter N times per iteration and store in an array? Angular 2 Cannot find control with unspecified name attribute on formArrays What is the difference between i = i + 1 and i += 1 in a 'for' loop? Prime numbers between 1 to 100 in C Programming Language Python Loop: List Index Out of Range JavaScript: Difference between .forEach() and .map() Why does using from __future__ import print_function breaks Python2-style print? Creating an array from a text file in Bash Iterate through dictionary values? C# Wait until condition is true

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor