75

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;
    }
Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43
eiu165
  • 6,101
  • 10
  • 41
  • 59
  • 1
    Sorry, but could you be more clear please, What is the final thing that you want to achieve ? you just made a multidimensional array inside the obj, Thanks – Mahesh Velaga Dec 09 '09 at 20:11
  • the multidimensional array inside the obj was a mistake. I wanted to turn the following JSON into a table. var obj = { 'players': [ { 'fname': 'joe', 'lname': 'smith', 'number': '34' }, { 'fname': 'jim', 'lname': 'jones', 'number': '12' }, { 'fname': 'jack', 'lname': 'Hoff', 'number': '84' } ] }; thanks – eiu165 Dec 09 '09 at 21:01

2 Answers2

122

Use for...in loop:

for (var key in obj) {
   console.log(' name=' + key + ' value=' + obj[key]);

   // do some more stuff with obj[key]
}
jldupont
  • 93,734
  • 56
  • 203
  • 318
  • Does this work? I thought you needed '[each](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for_each...in)'. – ki9 Nov 25 '15 at 00:12
  • 1
    when a json object has only one property, how can you acces the name and value of this property without iterating? – Gobliins Mar 22 '18 at 12:51
  • 1
    `Object.keys(obj)[0]` will get you the key and then you can use it as the key to get the value e.g. `obj[Object.keys(obj)[0]]` . . . I'm not sure why you would want to do this though? – joshuatvernon Mar 04 '19 at 10:59
46

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.

rab
  • 4,134
  • 1
  • 29
  • 42